<?php

   # Source Assessment Library of Functions

   function createProject($listobject,$projectname) {
      # create new project entry
     $listobject->querystring = "insert into project (projectname) values ('$projectname')";
     $listobject->performQuery();
     $listobject->querystring = "select projectid from project where projectname = '$projectname'";
     $listobject->performQuery();
      $projectid = $listobject->getRecordValue(1,'projectid');
      $listobject->querystring = "update project set workdir = 'proj$projectid' where projectid = $projectid";
     $listobject->performQuery();
     $listobject->querystring = "insert into hspf_globals (projectid) values ($projectid)";
     $listobject->performQuery();
     shell_exec("mkdir ./dir/proj$projectid");
     $listobject->querystring = "insert into seggroups (groupname, seglist, segtype, projectid) ";
     $listobject->querystring .= " values ('** All Segments **', '', 1, $projectid) ";
     $listobject->performQuery();


      return $projectid;
   }

   function getProjInfo($listobject, $projectid) {
      $listobject->querystring = "select * from project where projectid = $projectid";
      $listobject->performQuery();
      return $listobject->queryrecords[0];
   }

   function getHSPFGlobals($listobject, $projectid) {
      $listobject->querystring = "select * from hspf_globals where projectid = $projectid";
      $listobject->performQuery();
      return $listobject->queryrecords[0];
   }


   function initializeProject($listobject, $projectid) {

      if ($projectid == '') {
         $projectid = -1;
      }
      $projectexists = $listobject->valueExists('project','projectid',$projectid);

      if ($projectexists) {
         # copy landuses
         $listobject->querystring = "delete from landuses where projectid = $projectid";
         $listobject->performQuery();
         $listobject->querystring = "insert into landuses (landuseid, projectid, landusetype, landuse, pct_impervious, lzetp, cepsc, wsqop, ioqc, aoqc, sqolim) select a.landuseid, $projectid, a.landusetype, a.landuse, a.pct_impervious, a.lzetp, a.cepsc, a.wsqop, a.ioqc, a.aoqc, a.sqolim from landuses as a where a.projectid = 1";
         $listobject->performQuery();

         # create a default set of monthly parameters
         $listobject->querystring = "delete from hspfmonthly where projectid = $projectid";
         $listobject->performQuery();
         $listobject->querystring = "insert into hspfmonthly ( distrodomain, paramname, subshedid, projectid, landuseid, distroname, JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC) select distrodomain, paramname, subshedid, $projectid, landuseid, distroname, JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC from hspfmonthly as a where a.projectid = 1";
         $listobject->performQuery();

         # insert 1s for all that are not covered in the defaults
         $listobject->querystring = "insert into hspfmonthly ( distrodomain, paramname, subshedid, projectid, landuseid, distroname, JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC) select 'landuse', 'cepsc', 0, $projectid, landuseid, 'CEPSC monthly on ' || landuse, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 from landuses where projectid = 1 and landuseid not in (select landuseid from hspfmonthly where projectid = 1 and paramname = 'cepsc')";
         $listobject->performQuery();
         $listobject->querystring = "insert into hspfmonthly ( distrodomain, paramname, subshedid, projectid, landuseid, distroname, JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC) select 'landuse', 'nsur', 0, $projectid, landuseid, 'NSUR monthly on ' || landuse, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 from landuses where projectid = 1 and landuseid not in (select landuseid from hspfmonthly where projectid = 1 and paramname = 'nsur')";
         $listobject->performQuery();
         $listobject->querystring = "insert into hspfmonthly ( distrodomain, paramname, subshedid, projectid, landuseid, distroname, JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC) select 'landuse', 'lzetp', 0, $projectid, landuseid, 'LZETP monthly on ' || landuse, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 from landuses where projectid = 1 and landuseid not in (select landuseid from hspfmonthly where projectid = 1 and paramname = 'lzetp')";
         $listobject->performQuery();
         $listobject->querystring = "insert into hspfmonthly ( distrodomain, paramname, subshedid, projectid, landuseid, distroname, JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC) select 'landuse', 'uzsn', 0, $projectid, landuseid, 'UZSN monthly on ' || landuse, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 from landuses where projectid = 1 and landuseid not in (select landuseid from hspfmonthly where projectid = 1 and paramname = 'uzsn')";
         $listobject->performQuery();


       $listobject->querystring = "delete from subshed where projectid = $projectid";
         $listobject->performQuery();

         # load sources by copying default set
         $listobject->querystring = "delete from sources where projectid = $projectid";
         $listobject->performQuery();

         # delete old waste distributions
         $listobject->querystring = "delete from monthlydistro where projectid = $projectid";
         $listobject->performQuery();

         # load default waste distributions for nutrient management acres - standard
         # non-affiliated distributions for fertilizer application
         $listobject->querystring = "insert into monthlydistro (spreadid, projectid, landuseid, distroname, JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC) select 5, $projectid, a.landuseid, a.distroname, a.JAN, a.FEB, a.MAR, a.APR, a.MAY, a.JUN, a.JUL, a.AUG, a.SEP, a.OCT, a.NOV, a.DEC from distrodefaults as a WHERE a.spreadid = 5";
         #print("$listobject->querystring ; <br>");

         # remove any old reach stuff
         $listobject->querystring = "delete from projreaches where projectid = $projectid";
         $listobject->performQuery();

         # remove any old sublu stuff
         $listobject->querystring = "delete from subluparams where projectid = $projectid";
         $listobject->performQuery();

         # copy default calibration multipliers (1.0)
         $listobject->querystring = "insert into subluparams (projectid, sublu,subshedid,  luname, paramtype, forest, lzsn, infilt, lsur, slsur, kvary, agwrc, petmax, petmin, infexp, infild, deepfr, basetp, agwetp, cepsc, uzsn, nsur, intfw, irc, lzetp, ceps, surs, uzs, ifws, lzs, agws, gwvs) select $projectid, sublu,subshedid,  luname, paramtype, forest, lzsn, infilt, lsur, slsur, kvary, agwrc, petmax, petmin, infexp, infild, deepfr, basetp, agwetp, cepsc, uzsn, nsur, intfw, irc, lzetp, ceps, surs, uzs, ifws, lzs, agws, gwvs from subluparams where paramtype = 'multiplier' and projectid = 1";
         $listobject->performQuery();

         # copy default calibration offsets (0.0)
         $listobject->querystring = "insert into subluparams (projectid, sublu,subshedid,  luname, paramtype, forest, lzsn, infilt, lsur, slsur, kvary, agwrc, petmax, petmin, infexp, infild, deepfr, basetp, agwetp, cepsc, uzsn, nsur, intfw, irc, lzetp, ceps, surs, uzs, ifws, lzs, agws, gwvs) select $projectid, sublu,subshedid,  luname, paramtype, forest, lzsn, infilt, lsur, slsur, kvary, agwrc, petmax, petmin, infexp, infild, deepfr, basetp, agwetp, cepsc, uzsn, nsur, intfw, irc, lzetp, ceps, surs, uzs, ifws, lzs, agws, gwvs from subluparams where paramtype = 'offset' and projectid = 1";
         $listobject->performQuery();

         # copy default source load types
         $listobject->querystring = "insert into sourceloadtype (sourcename , auweight, pollutantprod, produnits, pollutantconc, storagedieoff, concunits, conv, convunits, projectid) select a.sourcename , a.auweight, a.pollutantprod, a.produnits, a.pollutantconc, a.storagedieoff, a.concunits, a.conv, a.convunits, $projectid from sourceloadtype as a where a.projectid = 1";
         $listobject->performQuery();

         # remove any old BMP stuff
         $listobject->querystring = "delete from bmp_subtypes where projectid = $projectid";
         $listobject->performQuery();
         $listobject->querystring = "delete from bmp_types where projectid = $projectid";
         $listobject->performQuery();

         # copy default bmp types
         $listobject->querystring = "insert into bmp_types (projectid, bmp_name, bmp_desc) select $projectid, bmp_name, bmp_desc from bmp_types where projectid = 1;";
         $listobject->performQuery();

         # copy default bmp subtypes linked to the new BMPs
         $listobject->querystring = " insert into bmp_subtypes (projectid, bmpname, bmptext, typeid, bmp_units, neffic, ";
         $listobject->querystring .= " peffic, seffic, efftype)  ";
         $listobject->querystring .= "select $projectid, a.bmpname, a.bmptext, b.typeid, a.bmp_units, a.neffic, a.peffic,  ";
         $listobject->querystring .= "a.seffic, a.efftype ";
         $listobject->querystring .= " from bmp_subtypes as a, ";
         $listobject->querystring .= "    (select a.typeid as oldid, b.typeid ";
         $listobject->querystring .= "    from bmp_types as a, bmp_types as b ";
         $listobject->querystring .= "    where a.bmp_name = b.bmp_name ";
         $listobject->querystring .= "       and a.projectid = 1 ";
         $listobject->querystring .= "       and b.projectid = $projectid ";
         $listobject->querystring .= "   ) as b ";
         $listobject->querystring .= " where a.typeid = b.oldid;";
         $listobject->performQuery();

        # copy baseline BMP info
       # insert into bmp_types (bmp_name, bmp_desc, projectid, hist_luchange, efftype)
       # select bmp_name, bmp_desc, $projectid, hist_luchange, efftype from bmp_types where projectid = 1;

       #insert into bmp_subtypes (bmpname, bmptext, typeid, bmp_units, neffic, peffic, seffic,
       #efftype, projectid, destlu, annual, naffect_area, paffect_area, saffect_area, conversion,
       #comments, convunits)
       #select a.bmpname, a.bmptext, b.typeid, a.bmp_units, a.neffic, a.peffic, a.seffic, a.efftype, 97,
       #a.destlu, a.annual, a.naffect_area, a.paffect_area, a.saffect_area, a.conversion, a.comments, a.convunits
       #from bmp_subtypes as a,
       #   (select a.typeid, b.typeid as baseid
       #    from bmp_types as a, bmp_types as b
       #    where a.projectid = 97
       #    and b.projectid = 65
       #    and a.bmp_name = b.bmp_name
       #   ) as b
       #where a.projectid = 65
       #   and a.typeid = b.baseid;

       #insert into proj_bmp_order (typeid, bmp_group,bmp_order, projectid)
       #select b.typeid, a.bmp_group, a.bmp_order, 97
       # from proj_bmp_order as a,
       #   (select a.typeid, b.typeid as baseid
       #    from bmp_types as a, bmp_types as b
       #    where a.projectid = 97 and b.projectid = 65 and a.bmp_name = b.bmp_name
       #   ) as b
       #where a.projectid = 65 and a.typeid = b.baseid;




      }
   } /* end initializeProject */

   function updateProject($listobject,$projectid, $projectname) {
      # updates project entry
        $listobject->querystring = "update project set projectname = '$projectname' where projectid = $projectid";
     $listobject->performQuery();
   }


   function deleteProject($listobject,$projectid) {
      # updates project entry
        $listobject->querystring = "delete from project where projectid = $projectid";
        #print("$listobject->querystring ; <br>");
     $listobject->performQuery();
   }

   function updateHSPFLUMap($listobject,$projectid) {
      # updates landuse map entry
        $listobject->querystring = "delete from map_hspf_lu where hspf_lu not in (select distinct(luname) from subluparams where projectid = $projectid) and projectid = $projectid";
     $listobject->performQuery();
        $listobject->querystring = "insert into map_hspf_lu(projectid,hspf_lu) select projectid,luname from subluparams where projectid = $projectid and luname not in (select hspf_lu from map_hspf_lu where projectid = $projectid) group by projectid,luname";
     $listobject->performQuery();
   }

   function updateHSPFGlobals($listobject,$invars) {

      $wdm1 = $invars['wdm1'];
      $wdm2 = $invars['wdm2'];
      $wdm3 = $invars['wdm3'];
      $wdm4 = $invars['wdm4'];
      $startdate = $invars['startdate'];
      $enddate = $invars['enddate'];
      $projectid = $invars['projectid'];
      $imppct = $invars['imppct'];
      $ucifile = $invars['ucifile'];
      $precip_wdm_id = $invars['precip_wdm_id'];
      $evap_wdm_id = $invars['evap_wdm_id'];
      $reach_wdm_id1 = $invars['reach_wdm_id1'];
      $reachid1 = $invars['reachid1'];
      $reach_wdm_id2 = $invars['reach_wdm_id2'];
      $reachid2 = $invars['reachid2'];
      $copyreaches = $invars['copyreaches'];
      $copysubsheds = $invars['copysubsheds'];
      $useftablefile = $invars['useftablefile'];
      $ftablefile = $invars['ftablefile'];
      $usehydromonfile = $invars['usehydromonfile'];
      $hydromonfile = $invars['hydromonfile'];
      $if = $invars['if'];
      $ro = $invars['ro'];
      $usethiessen = $invars['usethiessen'];
      $usegqual = $invars['usegqual'];
      $depwater = $invars['depwater'];
      $fcreach = $invars['fcreach'];
      $trackruns = $invars['trackruns'];
      $consqual = $invars['consqual'];
      $timestep = $invars['timestep'];
      $calcioqcsqolim = $invars['calcioqcsqolim'];
      $monioqc = $invars['monioqc'];
      $allowagwetp = $invars['allowagwetp'];
      $impwashoff = $invars['impwashoff'];
      $zerodate = $invars['zerodate'];

      if (strlen($startdate) == 0) {
         $startdate = date();
      }
      if (strlen($enddate) == 0) {
         $enddate = date();
      }
      if (strlen($precip_wdm_id) == 0) {
         $precip_wdm_id = -1;
      }
      if (strlen($evap_wdm_id) == 0) {
         $evap_wdm_id = -1;
      }
      if (strlen($reach_wdm_id1) == 0) {
         $reach_wdm_id1 = -1;
      }
      if (strlen($reachid1) == 0) {
         $reachid1 = -1;
      }
      if (strlen($reach_wdm_id2) == 0) {
         $reach_wdm_id2 = -1;
      }
      if (strlen($reachid2) == 0) {
         $reachid2 = -1;
      }

      $uzsn_mo = $invars['uzsn_mo'];
      $lzetp_mo = $invars['lzetp_mo'];
      $cepsc_mo = $invars['cepsc_mo'];
      $nsur_mo = $invars['nsur_mo'];

      $listobject->querystring = "update hspf_globals set timestep = $timestep, ucifile = '$ucifile',wdm1 = '$wdm1', wdm2 = '$wdm2', wdm3 = '$wdm3', wdm4 = '$wdm4', precip_wdm_id = '$precip_wdm_id', evap_wdm_id = '$evap_wdm_id', startdate = '$startdate', enddate = '$enddate', cepsc_mo = '$cepsc_mo', lzetp_mo = '$lzetp_mo', uzsn_mo = '$uzsn_mo', nsur_mo = '$nsur_mo', reach_wdm_id1 = '$reach_wdm_id1', reachid1 = '$reachid1', reach_wdm_id2 = '$reach_wdm_id2', reachid2 = '$reachid2', copysubsheds = '$copysubsheds', copyreaches = '$copyreaches', useftablefile = '$useftablefile', ftablefile = '$ftablefile', ro = '$ro', if = '$if', usethiessen = $usethiessen, usegqual = '$usegqual', consqual = '$consqual', depwater = $depwater, fcreach = '$fcreach', trackruns = '$trackruns', hydromonfile = '$hydromonfile', usehydromonfile = '$usehydromonfile', calcioqcsqolim = '$calcioqcsqolim', monioqc = '$monioqc', allowagwetp = $allowagwetp, impwashoff = $impwashoff, zerodate = '$zerodate' where projectid = $projectid";

      #print("$listobject->querystring ; <br>");
     $listobject->performQuery();

     if (isset($imppct)) {
        $impkeys = array_keys($imppct);
     } else {
        $impkeys = array();
     }

     foreach ($impkeys as $thiskey) {

        $thispct = $imppct[$thiskey];
        $listobject->querystring = "update landuses set pct_impervious = $thispct where projectid = $projectid and luid = $thiskey";
        $listobject->performQuery();
     }

   }

   function hspfGenInfoBlocks($listobject, $projectid, $uciobject, $perlndml, $implndml, $pertowetml, $imptowetml, $debug) {

       # SET up PERLND-GENINFO block
      $listobject->querystring = "insert into perlndgeninfo (segstart,luname) select sublu,luname from subluparams where projectid = $projectid and paramtype = 'parameter'";
      if ($debug == 1) { print("$listobject->querystring ; <br>"); }
      $listobject->performQuery();

      # set up RCHRES GEN-INFO table
      $pdef = $uciobject->ucitables['RGEN-INFO']['paramdefaults'];
      $pcol = $uciobject->ucitables['RGEN-INFO']['paramcolumns'];
         $listobject->querystring = "insert into rchresgeninfo (segstart,$pcol) select reachid,$pdef from projreaches where projectid = $projectid";
         if ($debug == 1) { print("$listobject->querystring ; <br>"); }
      $listobject->performQuery();

      # set up impervious land uses
      $uciobject->initImperv();
      $listobject->querystring = "create temp table implndareas as select a.sublu as segstart,c.hspf_lu as luname,a.subshedid, trunc((a.luarea * b.pct_impervious)::numeric,2) as lndarea from subluparams as a, landuses as b, map_hspf_lu as c where a.luname = c.hspf_lu and b.luid = c.project_luid and a.projectid = $projectid and c.projectid = $projectid and b.projectid = $projectid and b.pct_impervious > 0.0  and a.paramtype = 'parameter'";
         if ($debug == 1) { print("$listobject->querystring ; <br>"); }
      $listobject->performQuery();
      $listobject->querystring = "insert into implndgeninfo (segstart,luname) select segstart,luname from implndareas";
         if ($debug == 1) { print("$listobject->querystring ; <br>"); }
      $listobject->performQuery();


      # add IMPLND,PERLDN, and RCHRES to SCHEMATIC block
         $listobject->querystring = "insert into schematic (sname, ssegno, areafactor, dname, dsegno, mlno) select 'PERLND',sublu,trunc(luarea::numeric,2),'RCHRES',subshedid,$perlndml from subluparams where subluparams.projectid = $projectid  and subluparams.paramtype = 'parameter'";
      if ($debug == 1) { print("$listobject->querystring ; <br>"); }
      $listobject->performQuery();

      # update areas in SCHEMATIC PERLND's to reflect impervious areas
      $listobject->querystring = "update schematic set areafactor = trunc((areafactor - implndareas.lndarea)::numeric,2) where schematic.ssegno = implndareas.segstart and schematic.sname = 'PERLND' and schematic.dname = 'RCHRES'";
      if ($debug == 1) { print("$listobject->querystring ; <br>"); }
      $listobject->performQuery();

        # get stream linkage from projreach table
         $listobject->querystring = "create temp table rchlinks as select a.reachid as reachid,b.reachid as nextreach from projreaches as a, projreaches as b where a.to_node = b.from_node and a.projectid = $projectid and b.projectid = $projectid";
      $listobject->performQuery();
      $listobject->querystring = "insert into schematic (sname, ssegno, dname, dsegno, mlno) select 'RCHRES',reachid,'RCHRES',nextreach,3 from rchlinks where nextreach in (select reachid from projreaches where projectid = $projectid) and reachid <> nextreach";
      $listobject->performQuery();

      $listobject->querystring = "insert into schematic (sname, ssegno, areafactor, dname, dsegno, mlno) select 'IMPLND',segstart,lndarea,'RCHRES',subshedid,$implndml from implndareas";
      if ($debug == 1) { print("$listobject->querystring ; <br>"); }
      $listobject->performQuery();
      if ($debug == 1) { $listobject->showlist(); }


         # do summaries before updating wetland stuff to ratios
         $listobject->querystring = "select sum(areafactor) as area from schematic where sname in ('PERLND', 'IMPLND') and dname in ('PERLND', 'IMPLND', 'RCHRES')";
         $listobject->performQuery();
         $tarea = $listobject->getRecordValue(1,'area');
         $farea = number_format($tarea, 1);

         $listobject->querystring = "select a.luname, sum(b.areafactor) as area from perlndgeninfo as a, schematic as b where a.segstart = b.ssegno and b.sname = 'PERLND' and dname in ('PERLND', 'IMPLND', 'RCHRES') group by a.luname";
         $listobject->performQuery();
         $plusum = $listobject->queryrecords;

         $listobject->querystring = "select a.luname, sum(b.areafactor) || ' acres' as area from perlndgeninfo as a, schematic as b where a.segstart = b.ssegno and b.sname = 'IMPLND' and dname in ('PERLND', 'IMPLND', 'RCHRES') group by a.luname";
         $listobject->performQuery();
         $ilusum = $listobject->queryrecords;


        # create wetland linkages if they are being modeled
        # do for IMPLNDs
      # convert areas into ratios for implnd/perlnd to perlnd linkages
      $listobject->querystring = "update schematic set mlno = $pertowetml, dname = 'PERLND', dsegno = a.sublu, areafactor = trunc((areafactor/a.luarea)::numeric,4) from subluparams as a, subluparams as b where sname = 'PERLND' and dname = 'RCHRES' and b.ripbuffer <> 't' and ssegno = b.sublu and b.subshedid = a.subshedid and a.ripbuffer = 't' and a.projectid = $projectid and b.projectid = $projectid";
      if ($debug == 1) { print("$listobject->querystring ; <br>"); }
      $listobject->performQuery();
      if ($debug == 1) { $listobject->showlist(); }

      # repeat for IMPLNDs
      # convert areas into ratios for implnd/perlnd to perlnd linkages
      $listobject->querystring = "update schematic set mlno = $imptowetml, dname = 'PERLND', dsegno = a.sublu, areafactor = trunc((areafactor/a.luarea)::numeric,6) from subluparams as a, subluparams as b where sname = 'IMPLND' and dname = 'RCHRES' and b.ripbuffer <> 't' and ssegno = b.sublu and b.subshedid = a.subshedid and a.ripbuffer = 't' and a.projectid = $projectid and b.projectid = $projectid";
      if ($debug == 1) { print("$listobject->querystring ; <br>"); }
      $listobject->performQuery();
      if ($debug == 1) { $listobject->showlist(); }

      $retarray = array($farea, $iarea, $plusum, $ilusum);
      return $retarray;

   }


   function editSource($listobject, $sourcefields) {

      $sourceid = $sourcefields['sourceid'];
      $typeid = $sourcefields['typeid'];
      $poplink = $sourcefields['poplink'];
      $sourcename = $sourcefields['sourcename'];
      $avgweight = $sourcefields['avgweight'];

      $listobject->querystring = "update sources set sourcename = '$sourcename', typeid = $typeid, avgweight = $avgweight, poplink = $poplink where sourceid = $sourceid";
      $listobject->performQuery();

      print("$listobject->querystring ; <br>");

   }

   function deleteSource($listobject, $sourcefields) {

      $sourceid = $sourcefields['sourceid'];

      $listobject->querystring = "delete from sources where sourceid = $sourceid";
      $listobject->performQuery();
      #$listobject->querystring = "delete from subshed where sourceid = $sourceid";
      #$listobject->performQuery();

      #print("$listobject->querystring ; <br>");

   }

   function deleteSourceType($listobject, $sourcefields) {

      $typeid = $sourcefields['typeid'];

      $listobject->querystring = "delete from sourceloadtype where typeid = $typeid";
      $listobject->performQuery();

      #print("$listobject->querystring ; <br>");

   }

   function updateChild($listobject, $child_fields, $childprojectid, $tablename, $pkcol, $push, $debug) {

      $listobject->querystring = "update $tablename set ";

      $cols = '';
      $cdel = '';

      foreach ($child_fields as $thisfield) {
         $cols .= "$cdel $thisfield = a.$thisfield";
         $cdel = ',';
      }

      $whereclause = "where $tablename.parentid = a.$pkcol and $tablename.projectid = $childprojectid";

      if (!$push) {
         $whereclause .= " and inheritmode = 1";
      }

      $listobject->querystring .= "$cols from $tablename as a $whereclause";
      $listobject->performQuery();

      print("$listobject->querystring ; <br>");

   }

   function changeDistro($listobject, $sourceid, $projectid, $distrotype) {
      $listobject->querystring = "update sources set distrotype = $distrotype where sourceid = $sourceid";
      $listobject->performQuery();
      #print("$listobject->querystring ; <br>");
      $listobject->querystring = "delete from monthlydistro where projectid = $projectid and sourceid = $sourceid";
      $listobject->performQuery();
      #print("$listobject->querystring ; <br>");
      $listobject->querystring = "insert into monthlydistro (spreadid, sourcetype, sourceid,projectid, landuseid, distroname, JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC) select a.spreadid, b.typeid, $sourceid, $projectid, c.luid, a.distroname, a.JAN, a.FEB, a.MAR, a.APR, a.MAY, a.JUN, a.JUL, a.AUG, a.SEP, a.OCT, a.NOV, a.DEC from distrodefaults as a, sources as b, landuses as c where b.sourceid = $sourceid and a.distrotype = b.distrotype and c.landuseid = a.landuseid and c.projectid = $projectid";
      #print("$listobject->querystring ; <br>");
      $listobject->performQuery();
   }

   function copyDistro($listobject, $sourceid, $projectid, $copysourceid) {

      $listobject->querystring = "delete from monthlydistro where projectid = $projectid and sourceid = $sourceid";
      $listobject->performQuery();
      print("$listobject->querystring ; <br>");

      $listobject->querystring = "select typeid from sources where projectid = $projectid and sourceid = $sourceid";
      $listobject->performQuery();
     $typeid = $listobject->getRecordValue(1,'typeid');
      print("$listobject->querystring ; <br>");

      $listobject->querystring = "insert into monthlydistro (spreadid, sourcetype, sourceid,projectid, landuseid, distroname, JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC) select a.spreadid, $typeid, $sourceid, $projectid, a.landuseid, a.distroname, a.JAN, a.FEB, a.MAR, a.APR, a.MAY, a.JUN, a.JUL, a.AUG, a.SEP, a.OCT, a.NOV, a.DEC from monthlydistro as a where a.sourceid = $copysourceid and a.projectid = $projectid";
      print("$listobject->querystring ; <br>");
      $listobject->performQuery();

   }


   function calcQualParams($listobject, $projectid, $calcioqcsqolim, $debug) {

      $paramlist = array('wsqop', 'sqolim','ioqc','aoqc','sqo');
      $adjlist = array();

      foreach ($paramlist as $thisparm) {
         $listobject->querystring = "create temp table qualparm_tmp as select a.sublu as segstart, a.subshedid as subshedid, a.luname as luname, b.wsqop as wsqop, b.ioqc as ioqc, b.aoqc as aoqc, b.sqo as sqo, b.sqolim as sqolim from subluparams as a, pqualinput as b where a.projectid = $projectid and a.paramtype = 'parameter' and a.sublu = b.segstart";
         $listobject->performQuery();
         $listobject->querystring = "select adj_id,subwatersheds from adjustments where projectid = $projectid and paramname = '$thisparm' ORDER by subwatersheds DESC";
         $listobject->performQuery();
         $adjs = $listobject->queryrecords;

         $parmcap = strtoupper($thisparm);
         if ($debug == 1) {  print("Adjustments for $parmcap <br>"); }


         if (count($adjs) == 0) {
            print("<br><b>Warning:</b> There are no adjustments entered for $parmcap, thus, $parmcap will be set to a default value.<br>");
         }
         $adjsheds = '';
         $adjdelim = '';
         $unadjsql = '';
         $iunadsql = '';
         # get base factors without landuse adjustments, for each group of adjustments
         foreach ($adjs as $thisrec) {
            $subsheds = $thisrec['subwatersheds'];
            $adjid = $thisrec['adj_id'];
            if ($subsheds <> '') {
               $whereclause = "qualparm_tmp.luname = c.hspf_lu and c.projectid = $projectid and b.luid = c.mapid and qualparm_tmp.subshedid in ($subsheds) and b.adj_id = $adjid";
               $subtext = "($subsheds)";
               $adjsheds .= "$adjdelim$subsheds";
               $adjdelim = ',';
               $unadjsql = "and subshedid not in ($adjsheds)";
               $iadsql = "and d.segstart in ( select sublu from subluparams where projectid = $projectid and paramtype = 'parameter' and subshedid in ($subsheds) )";
               $iunadsql = "and d.segstart in ( select sublu from subluparams where projectid = $projectid and paramtype = 'parameter' and subshedid not in ($adjsheds))";
            } else {
               $whereclause = "qualparm_tmp.luname = c.hspf_lu and c.projectid = $projectid and b.luid = c.mapid and b.adj_id = $adjid $unadjsql";
               $subtext = 'All';
               $iadsql = '';
            }


            # adjust for land use
            if ($calcioqcsqolim and ($thisparm == 'ioqc')) {
               if ($subsheds == '') {
                  $isq = $iunadsql;
               } else {
                  $isq = $iadsql;
               }
               $listobject->querystring = "update qualparm_tmp set ioqc = (qualparm_tmp.sqo * b.adjfact) from lu_adj as b, map_hspf_lu as c where $whereclause";
               # create summary of adjustments query
               $sumq = "select a.hspf_lu, c.adjfact, (avg((b.JAN + b.FEB + b.MAR + b.APR + b.MAY + b.JUN + b.JUL + b.AUG + b.SEP + b.OCT + b.NOV + b.DEC)/12.0) / 283.17) as avgioqc from map_hspf_lu as a, pmonioqc as b, lu_adj as c, perlndgeninfo as d where c.adj_id = $adjid and a.mapid = c.luid and b.segstart = d.segstart and d.luname = a.hspf_lu $isq group by a.hspf_lu, c.adjfact";
            } else {
               $listobject->querystring = "update qualparm_tmp set $thisparm = (qualparm_tmp.$thisparm * b.adjfact) from lu_adj as b, map_hspf_lu as c where $whereclause";
               # create summary of adjustments
               $sumq = "select a.hspf_lu, b.adjfact from map_hspf_lu as a, lu_adj as b where b.adj_id = $adjid and a.mapid = b.luid";
            }
            if ($debug == 1) {  print("$listobject->querystring ; <br>"); }
            $listobject->performQuery();

            # get factors to report in UCI
            $adjstring = "*** $parmcap";
            $adjstring .= ": sub-sheds - $subtext";
            array_push($adjlist, $adjstring);
            $listobject->querystring = $sumq;
            if ($debug == 1) {  print("$listobject->querystring ; <br>"); }
            #print("$listobject->querystring ; <br>");
            $listobject->performQuery();
            $adjrecs = $listobject->queryrecords;
            foreach($adjrecs as $arec) {
               $luname = $arec['hspf_lu'];
               $tadj = $arec['adjfact'];
               $ts = '';
               if ($calcioqcsqolim and ($thisparm == 'ioqc')) {
                  $tavg = number_format($arec['avgioqc'], 1);
                  $ts = "($tavg cfu/100mL)";
               }
               array_push($adjlist,"***     $luname : $tadj $ts");
               #print("$adjstring<br>");
               #print("***     $luname : $tadj<br>");

            }

         }

         $listobject->querystring = "update pqualinput set $thisparm = a.$thisparm from qualparm_tmp as a where pqualinput.segstart = a.segstart";
         $listobject->performQuery();
         if ($debug == 1) { print("$listobject->querystring ; <br>"); }

         $listobject->querystring = "drop table qualparm_tmp";
         $listobject->performQuery();


      }


      if ($debug == 1) {
         $listobject->querystring = "select * from pqualinput order by segstart";
         $listobject->performQuery();
         $listobject->tablename = '';
         $listobject->showList();
      }

      return $adjlist;

   }

   function createSubluSourceMap($listobject, $projectid, $debug) {

      if (!( $listobject->tableExists('sublusourcemap') )) {
         $listobject->querystring = "create temp table sublusourcemap as select a.sourceid, b.project_luid,c.luname, c.sublu, c.subshedid from monthlydistro as a, map_hspf_lu as b, subluparams as c where a.projectid = $projectid and b.projectid = $projectid and c.projectid = $projectid and a.spreadid = 1 and a.landuseid = b.project_luid and b.hspf_lu = c.luname and c.paramtype = 'parameter'";
         if ($debug == 1) { print("$listobject->querystring ; <br>"); }

         $listobject->performQuery();

         $listobject->querystring = "select * from sublusourcemap order by subshedid, sublu";
         $listobject->performQuery();
         if ($debug == 1) {
            $listobject->showList();
         }
      }

   }

   function makeIntLoadTable($listobject, $projectid, $startdate, $enddate, $debug) {


      createSubluSourceMap($listobject, $projectid, $debug);

      if (!( $listobject->tableExists('intsubloadchars') )) {
         # create a general table pulling together the characteristics
         # of the various intermittent loads by subwatershed
         # this table shows any intermittent loads, such as bio-soilds and
         # manure that is transferred into the watershed for application
         $listobject->querystring = "create temp table intsubloadchars as select a.sourceid, a.avgweight, c.storagedieoff, a.sourcename, b.appdate, b.subshedid, b.loadapplied as pollutantprod, 1 as popdens, 1 as actualpop, b.pollutantconc as appliedconc, c.pollutantconc, c.conv, c.auweight, c.typeid, c.sourceclass, a.distrotype, c.starttime, c.duration, 1.0 as meanpopfact";
         $listobject->querystring .= "    from sources as a,";
         $listobject->querystring .= "         int_sources as b,";
         $listobject->querystring .= "         sourceloadtype as c";
         $listobject->querystring .= "    where ";
         $listobject->querystring .= "        a.projectid = $projectid";
         $listobject->querystring .= "    and a.distrotype = 10";
         $listobject->querystring .= "    and b.projectid = $projectid";
         $listobject->querystring .= "    and b.appdate >= '$startdate'";
         $listobject->querystring .= "    and b.appdate <= '$enddate'";
         $listobject->querystring .= "    and c.projectid = $projectid";
         $listobject->querystring .= "    and b.sourceid = a.sourceid";
         $listobject->querystring .= "    and c.typeid = a.typeid";

         if ($debug == 1) { print("$listobject->querystring ; <br>"); }

         $listobject->performQuery();

         $listobject->querystring = "update intsubloadchars set pollutantconc = appliedconc where (appliedconc is not null) and (appliedconc > 0)";
         $listobject->performQuery();



         $listobject->querystring = "select * from intsubloadchars order by subshedid";
         $listobject->performQuery();
         if ($debug == 1) {
            $listobject->showList();
         }

         # create a temporary table linking subwatershed PERLND/IMPLND codes to
         # deposition sources
         $listobject->querystring = "create temp table adepsheds as select subshedid, sourceid, sourceclass from intsubloadchars group by subshedid, sourceid, sourceclass";
         if ($debug == 1) { print("$listobject->querystring ; <br>"); }
         $listobject->performQuery();

         # create a temporary table linking subwatershed PERLND/IMPLND codes to
         # deposition sources
         $listobject->querystring = "create temp table adepsegs as select b.subshedid, a.sourceid, a.sourceclass, b.sublu as segstart from adepsheds as a, sublusourcemap as b where b.subshedid = a.subshedid and b.sourceid = a.sourceid group by b.subshedid, a.sourceid, a.sourceclass, b.sublu";
         if ($debug == 1) { print("$listobject->querystring ; <br>"); }
         $listobject->performQuery();

         $listobject->querystring = "select * from adepsegs order by subshedid, segstart";
         $listobject->performQuery();
         if ($debug == 1) {
            $listobject->showList();
         }
      }
   }


   function makeLoadCharTable($listobject, $projectid, $debug) {

      # create a general table pulling together the characteristics
      # of the various loads by subwatershed
      # this table unites the sourceloadtype table with the sources table
      # including the source population, source production per AU/day
      $listobject->querystring = "create temp table subloadchars as select a.sourceid, a.avgweight, c.storagedieoff, a.sourcename, a.distrotype, b.subshedid, b.sourcepop as popdens, b.sourcepop as actualpop, c.pollutantconc, c.pollutantprod, c.conv, c.auweight, c.typeid, c.sourceclass, c.starttime, c.duration, 1.0 as meanpopfact";
      $listobject->querystring .= "    from sources as a,";
      $listobject->querystring .= "         subshed as b,";
      $listobject->querystring .= "         sourceloadtype as c";
      $listobject->querystring .= "    where ";
      $listobject->querystring .= "        a.projectid = $projectid";
      $listobject->querystring .= "    and a.distrotype not in (10)";
      $listobject->querystring .= "    and b.projectid = $projectid";
      $listobject->querystring .= "    and c.projectid = $projectid";
      $listobject->querystring .= "    and b.sourceid = a.sourceid";
      $listobject->querystring .= "    and c.typeid = a.typeid";

      if ($debug == 1) { print("$listobject->querystring ; <br>"); }

      $listobject->performQuery();

      $listobject->querystring = "update subloadchars set meanpopfact = ((b.JAN + b.FEB + b.MAR + b.APR + b.MAY + b.JUN + b.JUL + b.AUG + b.SEP + b.OCT + b.NOV + b.DEC ) / 12.0)  from monthlydistro as b where b.sourceid = subloadchars.sourceid and b.projectid = $projectid and b.spreadid = 3";
      $listobject->performQuery();


      $listobject->querystring = "select * from subloadchars order by subshedid";
      $listobject->performQuery();
      if ($debug == 1) {
         $listobject->showList();
      }

   }


   function subluInterp($listobject, $projectid, $thisyear, $sstable, $outtable, $debug, $adjrates = 1) {
      # copysubshed is the subshed info from this projectid

      $listobject->querystring = " CREATE TEMP TABLE nextsublu AS ";
      $listobject->querystring .= " SELECT subshedid, luname, min(nmluname) as nmluname, -888.8 as luarea, 1 as nm_planbase, ";
      $listobject->querystring .= "    -888.8 as maxp,  -888.8 as maxn, -888.8 as pct_nm,";
      $listobject->querystring .= "    -888.8 as total_p, -888.8 as total_n, ";
      $listobject->querystring .= "    -888.8 as legume_n, -888.8 as nrate, ";
      $listobject->querystring .= "    -888.8 as optn, -888.8 as optp, ";
      $listobject->querystring .= "    -888.8 as maxnrate, -888.8 as maxprate, ";
      $listobject->querystring .= "    -888.8 as prate, -888.8 as uptake_n, -888.8 as uptake_p, ";
      $listobject->querystring .= " min(thisyear) AS nextyear ";
      $listobject->querystring .= " FROM $sstable ";
      $listobject->querystring .= " WHERE thisyear > $thisyear  ";
      $listobject->querystring .= " and projectid = $projectid ";
      $listobject->querystring .= " GROUP BY subshedid, luname ";
      $listobject->performQuery();
      if ($debug) { print("$listobject->querystring ; <br>"); }

      # create  template for  previous year table
      $listobject->querystring = " CREATE TEMP TABLE prevsublu AS ";
      $listobject->querystring .= " SELECT subshedid, luname, min(nmluname) as nmluname, -888.8 as luarea, 1 as nm_planbase, ";
      $listobject->querystring .= "    -888.8 as maxp,  -888.8 as maxn, -888.8 as pct_nm, ";
      $listobject->querystring .= "    -888.8 as total_p,  -888.8 as total_n, -888.8 as legume_n, -888.8 as nrate, -888.8 as prate, -888.8 as uptake_n, -888.8 as uptake_p, ";
      $listobject->querystring .= "    -888.8 as optn, -888.8 as optp, ";
      $listobject->querystring .= "    -888.8 as maxnrate, -888.8 as maxprate, ";
      $listobject->querystring .= " max(thisyear) AS prevyear";
      $listobject->querystring .= " FROM $sstable";
      $listobject->querystring .= " WHERE thisyear < $thisyear ";
      $listobject->querystring .= " and projectid = $projectid ";
      $listobject->querystring .= " GROUP BY subshedid, luname";
      $listobject->performQuery();
      if ($debug) { print("$listobject->querystring ; <br>"); }

      $listobject->querystring = " CREATE TEMP TABLE interpsublu AS";
      $listobject->querystring .= " SELECT subshedid, luname, min(nmluname) as nmluname, -888.8 as luarea, ";
      $listobject->querystring .= "    -888.8 as maxp,  -888.8 as maxn, -888.8 as pct_nm, ";
      $listobject->querystring .= "    -888.8 as total_p,  -888.8 as total_n, -888.8 as legume_n, -888.8 as nrate, -888.8 as prate, -888.8 as uptake_n, -888.8 as uptake_p, ";
      $listobject->querystring .= "    -888.8 as optn, -888.8 as optp, ";
      $listobject->querystring .= "    -888.8 as maxnrate, -888.8 as maxprate, ";
      $listobject->querystring .= " $thisyear as thisyear, 1 as nm_planbase";
      $listobject->querystring .= " FROM $sstable ";
      $listobject->querystring .= " where projectid = $projectid ";
      $listobject->querystring .= " GROUP BY subshedid, luname";
      $listobject->performQuery();
      if ($debug) { print("$listobject->querystring ; <br>"); }

      # set values for previous reported year
      $listobject->querystring = " UPDATE nextsublu ";
      $listobject->querystring .= " SET luarea = $sstable.luarea, pct_nm = $sstable.pct_nm, ";
      $listobject->querystring .= " maxn = $sstable.maxn, maxp = $sstable.maxp, ";
      $listobject->querystring .= " total_n = $sstable.total_n, total_p = $sstable.total_p, nm_planbase = $sstable.nm_planbase, legume_n = $sstable.legume_n, ";
      $listobject->querystring .= " nrate = $sstable.nrate, prate = $sstable.prate, ";
      $listobject->querystring .= " maxnrate = $sstable.maxnrate, maxprate = $sstable.maxprate, ";
      $listobject->querystring .= " optn = $sstable.optn, optp = $sstable.optp, ";
      $listobject->querystring .= " uptake_n = $sstable.uptake_n, uptake_p = $sstable.uptake_p ";
      $listobject->querystring .= " WHERE ($sstable.thisyear=nextsublu.nextyear) ";
      $listobject->querystring .= "    AND ($sstable.luname=nextsublu.luname)  ";
      $listobject->querystring .= "    AND ($sstable.subshedid=nextsublu.subshedid)";
      $listobject->querystring .= "    AND ($sstable.luarea is not null)";
      $listobject->performQuery();
      if ($debug) { print("$listobject->querystring ; <br>"); }

      # set values for next reported year
      $listobject->querystring = " UPDATE prevsublu ";
      $listobject->querystring .= " SET luarea = $sstable.luarea, pct_nm = $sstable.pct_nm, ";
      $listobject->querystring .= " maxn = $sstable.maxn, maxp = $sstable.maxp, nm_planbase = $sstable.nm_planbase,  total_n = $sstable.total_n, total_p = $sstable.total_p, legume_n = $sstable.legume_n, ";
      $listobject->querystring .= " nrate = $sstable.nrate, prate = $sstable.prate, ";
      $listobject->querystring .= " maxnrate = $sstable.maxnrate, maxprate = $sstable.maxprate, ";
      $listobject->querystring .= " optn = $sstable.optn, optp = $sstable.optp, ";
      $listobject->querystring .= " uptake_n = $sstable.uptake_n, uptake_p = $sstable.uptake_p ";
      $listobject->querystring .= " WHERE ($sstable.thisyear = prevsublu.prevyear)  ";
      $listobject->querystring .= "    AND ($sstable.luname = prevsublu.luname)";
      $listobject->querystring .= "    AND ($sstable.subshedid = prevsublu.subshedid)";
      $listobject->querystring .= "    AND ($sstable.luarea is not null)";
      $listobject->performQuery();
      if ($debug) { print("$listobject->querystring ; <br>"); }

      # calculate change in area, ncapacity, and pcapacity per year between previous and next
      $listobject->querystring = " CREATE TEMP TABLE subludpdy AS ";
      $listobject->querystring .= " SELECT a.subshedid, a.luname, a.prevyear, ";
      $listobject->querystring .= " $thisyear as thisyear, a.nm_planbase, ";
      $listobject->querystring .= " a.luarea + ($thisyear - a.prevyear) * (((b.luarea-a.luarea)) / ((b.nextyear-a.prevyear)::float8)) AS luarea,";
      $listobject->querystring .= " a.maxp + ($thisyear - a.prevyear) * (((b.maxp-a.maxp)) / ((b.nextyear-a.prevyear)::float8)) AS maxp,";
      $listobject->querystring .= " a.maxn + ($thisyear - a.prevyear) * (((b.maxn-a.maxn)) / ((b.nextyear-a.prevyear)::float8)) AS maxn, ";
      $listobject->querystring .= " a.total_p + ($thisyear - a.prevyear) * (((b.total_p-a.total_p)) / ((b.nextyear-a.prevyear)::float8)) AS total_p,";
      $listobject->querystring .= " a.total_n + ($thisyear - a.prevyear) * (((b.total_n-a.total_n)) / ((b.nextyear-a.prevyear)::float8)) AS total_n, ";
      $listobject->querystring .= " a.legume_n + ($thisyear - a.prevyear) * (((b.legume_n-a.legume_n)) / ((b.nextyear-a.prevyear)::float8)) AS legume_n, ";

      $listobject->querystring .= " a.uptake_p + ($thisyear - a.prevyear) * (((b.uptake_p-a.uptake_p)) / ((b.nextyear-a.prevyear)::float8)) AS uptake_p, ";
      $listobject->querystring .= " a.uptake_n + ($thisyear - a.prevyear) * (((b.uptake_n-a.uptake_n)) / ((b.nextyear-a.prevyear)::float8)) AS uptake_n, ";

      $listobject->querystring .= " a.optn + ($thisyear - a.prevyear) * (((b.optn-a.optn)) / ((b.nextyear-a.prevyear)::float8)) AS optn, ";
      $listobject->querystring .= " a.optp + ($thisyear - a.prevyear) * (((b.optp-a.optp)) / ((b.nextyear-a.prevyear)::float8)) AS optp, ";
      $listobject->querystring .= " a.maxnrate + ($thisyear - a.prevyear) * (((b.maxnrate-a.maxnrate)) / ((b.nextyear-a.prevyear)::float8)) AS maxnrate, ";
      $listobject->querystring .= " a.maxprate + ($thisyear - a.prevyear) * (((b.maxprate-a.maxprate)) / ((b.nextyear-a.prevyear)::float8)) AS maxprate, ";

      $listobject->querystring .= " a.nrate + ($thisyear - a.prevyear) * (((b.nrate-a.nrate)) / ((b.nextyear-a.prevyear)::float8)) AS nrate, ";
      $listobject->querystring .= " a.prate + ($thisyear - a.prevyear) * (((b.prate-a.prate)) / ((b.nextyear-a.prevyear)::float8)) AS prate, ";
      # default the percent NM to previous year reported
      # we will update this later when considering BMPs, before adjusting landuses
      $listobject->querystring .= " a.pct_nm AS pct_nm ";
      $listobject->querystring .= " FROM prevsublu AS a, nextsublu AS b";
      $listobject->querystring .= " WHERE a.subshedid=b.subshedid ";
      $listobject->querystring .= "    And a.luname=b.luname ";
      $listobject->querystring .= "    and a.luarea <> -888.8";
      $listobject->querystring .= "    and b.luarea <> -888.8";
      $listobject->performQuery();
      if ($debug) { print("$listobject->querystring ; <br>"); }

      # if the year is an exact match, grab the corresponding entry
      $listobject->querystring = " UPDATE interpsublu SET luarea = $sstable.luarea, ";
      $listobject->querystring .= " maxp = $sstable.maxp, ";
      $listobject->querystring .= " pct_nm = $sstable.pct_nm, ";
      $listobject->querystring .= " maxn = $sstable.maxn, nm_planbase = $sstable.nm_planbase, ";
      $listobject->querystring .= " total_n = $sstable.total_n, total_p = $sstable.total_p, ";
      $listobject->querystring .= " nrate = $sstable.nrate, prate = $sstable.prate, ";
      $listobject->querystring .= " optn = $sstable.optn, optp = $sstable.optp, ";
      $listobject->querystring .= " maxnrate = $sstable.maxnrate, maxprate = $sstable.maxprate, ";
      $listobject->querystring .= " uptake_n = $sstable.uptake_n, uptake_p = $sstable.uptake_p, ";
      $listobject->querystring .= " legume_n = $sstable.legume_n ";
      $listobject->querystring .= " WHERE interpsublu.subshedid = $sstable.subshedid ";
      $listobject->querystring .= " AND interpsublu.luname = $sstable.luname ";
      $listobject->querystring .= " AND interpsublu.thisyear = $sstable.thisyear";
      $listobject->performQuery();
      if ($debug) { print("$listobject->querystring ; <br>"); }

      # otherwise, grab from the interpolation table
      $listobject->querystring = " UPDATE interpsublu SET luarea = subludpdy.luarea, ";
      $listobject->querystring .= " maxp = subludpdy.maxp, ";
      $listobject->querystring .= " pct_nm = subludpdy.pct_nm, ";
      $listobject->querystring .= " maxn = subludpdy.maxn, nm_planbase = subludpdy.nm_planbase, ";
      $listobject->querystring .= " total_n = subludpdy.total_n, total_p = subludpdy.total_p, ";
      $listobject->querystring .= " nrate = subludpdy.nrate, prate = subludpdy.prate, ";
      $listobject->querystring .= " optn = subludpdy.optn, optp = subludpdy.optp, ";
      $listobject->querystring .= " maxnrate = subludpdy.maxnrate, maxprate = subludpdy.maxprate, ";
      $listobject->querystring .= " legume_n = subludpdy.legume_n, ";
      $listobject->querystring .= " uptake_n = subludpdy.uptake_n, uptake_p = subludpdy.uptake_p ";
      $listobject->querystring .= " WHERE interpsublu.subshedid = subludpdy.subshedid ";
      $listobject->querystring .= " AND interpsublu.luname = subludpdy.luname ";
      $listobject->querystring .= " AND interpsublu.luarea = -888.8 ";
      $listobject->performQuery();
      if ($debug) { print("$listobject->querystring ; <br>"); }

      # if still not set, must be out of date range, so try the lower table
      # planbase = 1 unless it is reported this year, or an earlier year,
      # do not assume that planbase changes unless instructed
      $listobject->querystring = " UPDATE interpsublu set luarea = prevsublu.luarea, ";
      $listobject->querystring .= " maxp = prevsublu.maxp, ";
      $listobject->querystring .= " pct_nm = prevsublu.pct_nm, ";
      $listobject->querystring .= " maxn = prevsublu.maxn, nm_planbase = prevsublu.nm_planbase, ";
      $listobject->querystring .= " total_n = prevsublu.total_n, total_p = prevsublu.total_p, ";
      $listobject->querystring .= " nrate = prevsublu.nrate, prate = prevsublu.prate, ";
      $listobject->querystring .= " optn = prevsublu.optn, optp = prevsublu.optp, ";
      $listobject->querystring .= " maxnrate = prevsublu.maxnrate, maxprate = prevsublu.maxprate, ";
      $listobject->querystring .= " legume_n = prevsublu.legume_n, ";
      $listobject->querystring .= " uptake_n = prevsublu.uptake_n, uptake_p = prevsublu.uptake_p ";
      $listobject->querystring .= " WHERE interpsublu.luarea = -888.8 ";
      $listobject->querystring .= " AND interpsublu.luname = prevsublu.luname ";
      $listobject->querystring .= " AND interpsublu.subshedid = prevsublu.subshedid";
      $listobject->querystring .= " AND prevsublu.luarea <> -888.8";
      $listobject->performQuery();
      if ($debug) { print("$listobject->querystring ; <br>"); }

      # now try the upper table
      $listobject->querystring = " UPDATE interpsublu set luarea = nextsublu.luarea, ";
      $listobject->querystring .= " maxp = nextsublu.maxp, ";
      $listobject->querystring .= " pct_nm = nextsublu.pct_nm, ";
      $listobject->querystring .= " maxn = nextsublu.maxn, nm_planbase = nextsublu.nm_planbase, ";
      $listobject->querystring .= " total_n = nextsublu.total_n, total_p = nextsublu.total_p, ";
      $listobject->querystring .= " nrate = nextsublu.nrate, prate = nextsublu.prate, ";
      $listobject->querystring .= " optn = nextsublu.optn, optp = nextsublu.optp, ";
      $listobject->querystring .= " maxnrate = nextsublu.maxnrate, maxprate = nextsublu.maxprate, ";
      $listobject->querystring .= " legume_n = nextsublu.legume_n, ";
      $listobject->querystring .= " uptake_n = nextsublu.uptake_n, uptake_p = nextsublu.uptake_p ";
      $listobject->querystring .= " WHERE interpsublu.luarea = -888.8 ";
      $listobject->querystring .= " AND interpsublu.luname = nextsublu.luname ";
      $listobject->querystring .= " AND interpsublu.subshedid = nextsublu.subshedid";
      $listobject->querystring .= " AND nextsublu.luarea <> -888.8";
      $listobject->performQuery();
      if ($debug) { print("$listobject->querystring ; <br>"); }

      # create an out table, insure that each entry has a unique sublu, since these are
      # not referenced in any way, they are OK to be generated here on the fly
      $listobject->querystring = " create temp table $outtable ( ";
      $listobject->querystring .= " subshedid varchar(64), sublu SERIAL, legume_n float8, ";
      $listobject->querystring .= " luarea float8, total_n float8, total_p float8, ";
      $listobject->querystring .= " luname varchar(255), nmluname varchar(255), nm_planbase integer, ";
      $listobject->querystring .= " nrate float8, prate float8, ";
      $listobject->querystring .= " optn float8, optp float8, ";
      $listobject->querystring .= " maxnrate float8, maxprate float8, ";
      $listobject->querystring .= " uptake_n float8, uptake_p float8, ";
      $listobject->querystring .= " thisyear integer, projectid integer, ";
      $listobject->querystring .= " maxn float8, maxp float8, pct_nm float8 )";
      $listobject->performQuery();

      # this inserts values for each sublu, generating a unique sublu ID on the fly for later use
      $listobject->querystring = " insert into $outtable (luname, nmluname, luarea, subshedid, maxp, maxn, ";
      $listobject->querystring .= " total_n, total_p, pct_nm, nrate, prate, nm_planbase, legume_n, ";
      $listobject->querystring .= " uptake_n, uptake_p, optn, optp, maxnrate, maxprate, ";
      $listobject->querystring .= " thisyear, projectid) ";
      $listobject->querystring .= " select luname, nmluname, luarea, subshedid, maxp, maxn, ";
      $listobject->querystring .= " total_n, total_p, pct_nm, nrate, prate, nm_planbase, legume_n, ";
      $listobject->querystring .= " uptake_n, uptake_p, optn, optp, maxnrate, maxprate, ";
      $listobject->querystring .= " $thisyear, $projectid ";
      $listobject->querystring .= " from interpsublu";
      $listobject->performQuery();
      if ($debug) { print("$listobject->querystring ; <br>"); }

/*
      # kludge, kludge, kludge - setting max uptake on composite crops with rotations
      # and winter covers
      $listobject->querystring = "create temp table compland as select subshedid, sum(luarea) as comparea, avg(total_n) as total_n, avg(total_p) as total_p from $outtable where luname in ('lwm','hwm') group by $outtable.subshedid";
      $listobject->performQuery();

      $listobject->querystring = "update $outtable set maxn = (compland.total_n / compland.comparea), maxp = (compland.total_p / compland.comparea) where $outtable.luname in ('lwm','hwm') and $outtable.subshedid = compland.subshedid and compland.comparea > 0";
      $listobject->performQuery();

      # set the double crops totals
      $listobject->querystring = "update $outtable set total_n = maxn * luarea, total_p = maxp * luarea, uptake_n = maxn, uptake_p = maxp where luname in ('lwm','hwm') and luarea > 0";
      $listobject->performQuery();
*/

      if ($adjrates) {
         # adjust the crop need based on agronomic application rate.
         # the maxprate and maxnrate represents the maximum considered to be
         # safe without lamping the crops (really only applicable for nitrogen)
         # the maxn rate is calculated against uptake, so this will permit application on legumes if the maxnrate > 0.0
         #  and if their uptake is > 0.0, and if the amount of nutrients available is greater than the non-leguminous
         #  need in the county
         $listobject->querystring = " update $outtable set maxp = maxprate * uptake_p, maxn = maxnrate * uptake_n, optn = nrate * maxn, optp = prate * maxp ";

         # now, maxn is passed in from the crop yield routine as equivalent to uptake_n - fixation, therefore,
         # this DOES NOT accomodate the total maximum uptake
         #$listobject->querystring = " update $outtable set maxp = maxprate * maxp, maxn = maxnrate * maxn, optn = nrate * maxn, optp = prate * maxp where uptake_n > 0 and uptake_p > 0";
         $listobject->performQuery();
         if ($debug) { print("$listobject->querystring ; <br>"); }
      }


   }


   function popInterp($listobject, $projectid, $thisyear, $sstable, $debug) {
      # copysubshed is the subshed info from this projectid

      $listobject->querystring = " CREATE TEMP TABLE nextreport AS ";
      $listobject->querystring .= " SELECT subshedid, sourceid, -88888 as sourcepop,  ";
      $listobject->querystring .= " min(popyear) AS nextyear ";
      $listobject->querystring .= " FROM $sstable ";
      $listobject->querystring .= " WHERE popyear > $thisyear  ";
      $listobject->querystring .= " GROUP BY subshedid, sourceid ";
      $listobject->performQuery();
      #print("$listobject->querystring ; <br>");

      # create  template for  previous year table
      $listobject->querystring = " CREATE TEMP TABLE prevreport AS ";
      $listobject->querystring .= " SELECT subshedid, sourceid, -88888 as sourcepop, ";
      $listobject->querystring .= " max(popyear) AS prevyear";
      $listobject->querystring .= " FROM $sstable";
      $listobject->querystring .= " WHERE popyear < $thisyear ";
      $listobject->querystring .= " GROUP BY subshedid, sourceid";
      $listobject->performQuery();
      #print("$listobject->querystring ; <br>");

      $listobject->querystring = " CREATE TEMP TABLE worksubshed AS";
      $listobject->querystring .= " SELECT subshedid, sourceid, -88888 as sourcepop, 25 as src_citation, ";
      $listobject->querystring .= " $thisyear as thisyear";
      $listobject->querystring .= " FROM $sstable ";
      $listobject->querystring .= " GROUP BY subshedid, sourceid";
      $listobject->performQuery();
      #print("$listobject->querystring ; <br>");

      # set values for previous reported year
      $listobject->querystring = " UPDATE nextreport ";
      $listobject->querystring .= " SET sourcepop = $sstable.sourcepop";
      $listobject->querystring .= " WHERE ($sstable.popyear=nextreport.nextyear) ";
      $listobject->querystring .= "    AND ($sstable.sourceid=nextreport.sourceid)  ";
      $listobject->querystring .= "    AND ($sstable.subshedid=nextreport.subshedid)";
      $listobject->performQuery();
      #print("$listobject->querystring ; <br>");

      # set values for next reported year
      $listobject->querystring = " UPDATE prevreport ";
      $listobject->querystring .= " SET sourcepop = $sstable.sourcepop";
      $listobject->querystring .= " WHERE ($sstable.popyear = prevreport.prevyear)  ";
      $listobject->querystring .= "    AND ($sstable.sourceid = prevreport.sourceid)";
      $listobject->querystring .= "    AND ($sstable.subshedid = prevreport.subshedid)";
      $listobject->performQuery();
      #print("$listobject->querystring ; <br>");

      # calculate change in animals per year between previous and next
      $listobject->querystring = " CREATE TEMP TABLE dpdy AS ";
      $listobject->querystring .= " SELECT a.subshedid, a.sourceid, a.prevyear, ";
      $listobject->querystring .= " $thisyear as thisyear,  a.sourcepop as prevdata, ";
      $listobject->querystring .= " b.nextyear, b.sourcepop as nextdata, ";
      $listobject->querystring .= " ((b.sourcepop-a.sourcepop)::float8) / ((b.nextyear-a.prevyear)::float8) AS dpdy,";
      $listobject->querystring .= " -88888 AS sourcepop ";
      $listobject->querystring .= " FROM prevreport AS a, nextreport AS b";
      $listobject->querystring .= " WHERE a.subshedid=b.subshedid ";
      $listobject->querystring .= "    And a.sourceid=b.sourceid ";
      $listobject->querystring .= "    and a.sourcepop <> -88888";
      $listobject->querystring .= "    and b.sourcepop <> -88888";
      $listobject->performQuery();
      #print("$listobject->querystring ; <br>");

      # calcuale estimated interpolated population for each year in the table
      $listobject->querystring = " UPDATE dpdy SET sourcepop = ";
      $listobject->querystring .= " round( (prevdata+((thisyear - prevyear)*dpdy))::numeric, 0)";
      $listobject->querystring .= " where prevdata <> -88888";
      $listobject->performQuery();
      #print("$listobject->querystring ; <br>");

      # if the year is an exact match, grab the corresponding entry
      $listobject->querystring = " UPDATE worksubshed SET sourcepop = $sstable.sourcepop, ";
      $listobject->querystring .= " src_citation = $sstable.src_citation ";
      $listobject->querystring .= " WHERE worksubshed.subshedid = $sstable.subshedid ";
      $listobject->querystring .= " AND worksubshed.sourceid = $sstable.sourceid ";
      $listobject->querystring .= " AND worksubshed.thisyear = $sstable.popyear";
      $listobject->performQuery();
      #print("$listobject->querystring ; <br>");

      # otherwise, grab from the interpolation table
      $listobject->querystring = " UPDATE worksubshed SET sourcepop = dpdy.sourcepop ";
      $listobject->querystring .= " WHERE worksubshed.subshedid = dpdy.subshedid ";
      $listobject->querystring .= " AND worksubshed.sourceid = dpdy.sourceid ";
      $listobject->querystring .= " AND worksubshed.sourcepop = -88888 ";
      $listobject->performQuery();
      #print("$listobject->querystring ; <br>");

      # if still not set, must be out of date range, so try the lower table
      $listobject->querystring = " UPDATE worksubshed set sourcepop = prevreport.sourcepop ";
      $listobject->querystring .= " WHERE worksubshed.sourcepop = -88888 ";
      $listobject->querystring .= " AND worksubshed.sourceid = prevreport.sourceid ";
      $listobject->querystring .= " AND worksubshed.subshedid = prevreport.subshedid";
      $listobject->querystring .= " AND prevreport.sourcepop <> -88888";
      $listobject->performQuery();
      #print("$listobject->querystring ; <br>");

      # now try the upper table
      $listobject->querystring = " UPDATE worksubshed set sourcepop = nextreport.sourcepop ";
      $listobject->querystring .= " WHERE worksubshed.sourcepop = -88888 ";
      $listobject->querystring .= " AND worksubshed.sourceid = nextreport.sourceid ";
      $listobject->querystring .= " AND worksubshed.subshedid = nextreport.subshedid";
      $listobject->querystring .= " AND nextreport.sourcepop <> -88888";
      $listobject->performQuery();
      #print("$listobject->querystring ; <br>");
   }

   function makeTempWorkTables ($listobject, $projectid, $overwrite, $subsheds, $polltypes, $thisyear, $scenarioid, $debug, $hack_nm = 0) {
      # stashes the  contents of current projects working tables in
      # temporary tables in order  to optimize for  speed,
      # simplify the readabililty of sub-queries
      # eliminate the need for the use of projectid matches

       $prevdebug = $listobject->debug;
       $listobject->debug = $debug;

       $sublucolumns = "sublu, luname, nmluname, luarea, subshedid, thisyear, maxp, maxn, total_n, total_p, pct_nm, nrate, prate, nm_planbase, legume_n, uptake_n, uptake_p, optn, optp, maxnrate, maxprate, projectid";

       $subshedcolumns = "subshedid, sourceid, popyear, sourcepop, src_citation";

      if (strlen($subsheds) > 0) {
         # this expression was only necessary when the subshedid was a string
         # now it is integer, so we don;t need to convert and can pass
         # $subsheds directly into the query
         # this was slowing the queries down substantially since they
         # were forced to
         $subshedlist = "'" . join("','", explode(',', $subsheds)) . "'";
         $ssc = " and subshedid in ($subshedlist)";
      } else {
         $ssc = '';
      }

/*
      $listobject->querystring = "create temp table worksublu as ";
      $listobject->querystring .= "   select * from subluparams where ";
      $listobject->querystring .= "   projectid = $projectid ";
      $listobject->querystring .= "   and paramtype = 'parameter'";
      $listobject->querystring .= "   $ssc ";
      $listobject->performQuery();
      #print("$listobject->querystring ; <br>");

*/


      print("&nbsp;&nbsp;&nbsp;&nbsp; Creating Base SUBLU table <br>");
      $listobject->querystring = "create temp table rawsublu as ";
      $listobject->querystring .= "   select $sublucolumns from subluparams where ";
      $listobject->querystring .= "   projectid = $projectid ";
      $listobject->querystring .= "   and paramtype = 'parameter'";
      $listobject->querystring .= "   $ssc ";
      $listobject->performQuery();
      #print("$listobject->querystring ; <br>");

      print("&nbsp;&nbsp;&nbsp;&nbsp; Interpolating Base SUBLU table <br>");
      subluInterp($listobject, $projectid, $thisyear, 'rawsublu', 'worksublu', $debug);


      $listobject->querystring = "select count(*) as numsublu from worksublu";
      $listobject->performQuery();
      $numsublu = $listobject->getRecordValue(1,'numsublu');
      if ($numsublu == 0) {
         print("There are no subwatershed parameters for the requested subwatershed ID(s)");
         die;
      }
      #print("$listobject->querystring ; <br>");


      print("&nbsp;&nbsp;&nbsp;&nbsp; Creating Nutrient management table <br>");
      # modify the land use to reflect land use conversion BMPs etc.
      $listobject->querystring = "create temp table nm_sublu as ";
      $listobject->querystring .= "   select $sublucolumns from worksublu where ";
      $listobject->querystring .= "   pct_nm >= 0 and nmluname <> ''";
      $listobject->querystring .= "   and nmluname is not null";
      $listobject->performQuery();
      #print("$listobject->querystring ; <br>");

      $listobject->querystring = "update nm_sublu set luarea = pct_nm * luarea, ";
      $listobject->querystring .= "   maxn = optn, maxp = optp, maxnrate = nrate, maxprate = prate ";
      $listobject->performQuery();

      $listobject->querystring = "update worksublu set luarea = (1.0 - pct_nm) * luarea ";
      $listobject->querystring .= "   where pct_nm >= 0 and nmluname <> ''";
      $listobject->querystring .= "   and nmluname is not null";
      $listobject->performQuery();

      $listobject->querystring = "select max(sublu) as maxsublu from worksublu";
      $listobject->performQuery();
      $maxsublu = $listobject->getRecordValue(1,'maxsublu');

      $listobject->querystring = "update nm_sublu";
      $listobject->querystring .= "   set sublu = sublu + $maxsublu, luname = nmluname,";
      $listobject->querystring .= "      nmluname = luname";
      $listobject->performQuery();



      if ($hack_nm) {
         print("&nbsp;&nbsp;&nbsp;&nbsp; Forcing Nutrient management Rates <br>");
         # kludge - ugly, ugly, ugly
         # restores original maxn to back calculate for hacked in nutrient management rate.
         # this MUST be changed when we get ready for final calibration
         $listobject->querystring = " update nm_sublu set maxn = maxn / maxnrate  where maxnrate > 0";
         $listobject->performQuery();
         $listobject->querystring = " update nm_sublu set maxp = maxp / maxprate where maxprate > 0";
         $listobject->performQuery();
         #print("$listobject->querystring ; <br>");

         # this makes the maximum rate equal to crop removal, and optimal rate equal to non-leguminous crop removal,
         # which is good for legume, since it should limit
         # fixation if we were to over-apply beyond non-leguminous need, but still not exceed appropriate rates.
         $listobject->querystring = " update nm_sublu set maxp = 1.0 * uptake_p, maxn = 1.0 * uptake_n, optn = 1.0 * maxn, optp = 1.0 * maxp, nrate = 1.0, prate = 1.0 where uptake_n > 0 and uptake_p > 0";
         $listobject->performQuery();
         #print("$listobject->querystring ; <br>");
      }



      print("&nbsp;&nbsp;&nbsp;&nbsp; Inserting NM rates into working table <br>");
      $listobject->querystring = "insert into worksublu ($sublucolumns) select $sublucolumns from nm_sublu ";
      $listobject->performQuery();

/*
      $listobject->querystring = "select * from worksublu where subshedid = '42001' and luname in ('nhi', 'hwm')";
      $listobject->performQuery();
      $listobject->showList();
*/

      print("&nbsp;&nbsp;&nbsp;&nbsp; Creating Miscellanious Working Tables <br>");
      # create a column for parent landuse, for use in derived landuses such as
      # acres under nutrient mangament. These parent landuseids (planduseid) will be
      # used to connect these new derived landuses to pre-existing distributions
      $listobject->querystring = "create temp table worklanduses as ";
      $listobject->querystring .= "   select *, landuseid as planduseid from landuses where ";
      $listobject->querystring .= "   projectid = $projectid ";
      $listobject->performQuery();

/* # No longer Used
      $listobject->querystring = "create temp table worksublumult as ";
      $listobject->querystring .= "   select luname, nmluname, luarea, subshedid, maxp, maxn, total_n, total_p, pct_nm, nrate, prate, nm_planbase, legume_n, uptake_n, uptake_p, optn, optp, maxnrate, maxprate from subluparams where ";
      $listobject->querystring .= "   projectid = $projectid ";
      $listobject->querystring .= "   $ssc";
      $listobject->querystring .= "   and paramtype = 'multiplier'";
      $listobject->performQuery();
*/

      $listobject->querystring = "create temp table worksubluoffset as ";
      $listobject->querystring .= "   select $sublucolumns from subluparams where ";
      $listobject->querystring .= "   projectid = $projectid ";
      $listobject->querystring .= "   $ssc";
      $listobject->querystring .= "   and paramtype = 'offset'";
      $listobject->performQuery();

      print("&nbsp;&nbsp;&nbsp;&nbsp; Creating Distribution table <br>");
      $listobject->querystring = "create temp table workdistro as ";
      $listobject->querystring .= "   select a.subshedid, b.distroid, b.spreadid, b.sourceid, b.sourcetype, ";
      $listobject->querystring .= "      b.landuseid, b.distroname, b.jan, b.feb, b.mar, b.apr, b.may, b.jun, ";
      $listobject->querystring .= "      b.jul, b.aug, b.sep, b.oct, b.nov, b.dec, b.pct_need ";
      $listobject->querystring .= "   from (select subshedid from worksublu group by subshedid) as a, monthlydistro as b ";
      $listobject->querystring .= "   where b.projectid = $projectid ";
     # print("$listobject->querystring ; <br>");
      $listobject->performQuery();


      # now, update any custom distributions that have been passed in via local_apply table
      # this should be enhanced soon to include the interpolation of values in the local_apply table
      # between years. As it is, this will only affect the values if an exact match on "thisyear" exists
      # in the local_apply table.

      $listobject->querystring = " update workdistro set ";
      $listobject->querystring .= "    jan = a.jan, ";
      $listobject->querystring .= "    feb = a.feb, ";
      $listobject->querystring .= "    mar = a.mar, ";
      $listobject->querystring .= "    apr = a.apr, ";
      $listobject->querystring .= "    may = a.may, ";
      $listobject->querystring .= "    jun = a.jun, ";
      $listobject->querystring .= "    jul = a.jul, ";
      $listobject->querystring .= "    aug = a.aug, ";
      $listobject->querystring .= "    sep = a.sep, ";
      $listobject->querystring .= "    oct = a.oct, ";
      $listobject->querystring .= "    nov = a.nov, ";
      $listobject->querystring .= "    dec = a.dec, ";
      $listobject->querystring .= "    pct_need = a.need_pct ";
      $listobject->querystring .= " from local_apply as a, worklanduses as b, spreadtype as c ";
      $listobject->querystring .= " where workdistro.subshedid = a.subshedid ";
      $listobject->querystring .= "    and workdistro.landuseid = b.landuseid ";
      $listobject->querystring .= "    and workdistro.spreadid = c.spreadid ";
      $listobject->querystring .= "    and a.source_type = c.shortname ";
      $listobject->querystring .= "    and a.luname = b.hspflu ";
      $listobject->querystring .= "    and a.thisyear = $thisyear ";
      $listobject->querystring .= "    and a.projectid = $projectid ";
      $listobject->querystring .= "    and a.scenarioid = $scenarioid ";
      $listobject->performQuery();


      print("&nbsp;&nbsp;&nbsp;&nbsp; Copying Source Tables <br>");
/* # No longer Used
      $listobject->querystring = "create temp table workdistrolu as ";
      $listobject->querystring .= "   select a.spreadid, b.hspflu as luname ";
      $listobject->querystring .= " from workdistro as a, worklanduses as b  ";
      $listobject->querystring .= "   where b.landuseid = a.landuseid ";
      $listobject->querystring .= "      and a.spreadid not in ( 2, 3, 4, 9 ) ";
      $listobject->querystring .= "   group by a.spreadid, b.hspflu ";
      $listobject->performQuery();
*/

      $listobject->querystring = "create temp table worksourcepolls as ";
      $listobject->querystring .= "   select * from sourcepollutants where ";
      $listobject->querystring .= "   projectid = $projectid ";
      $listobject->performQuery();

      $listobject->querystring = "create temp table worksources as ";
      $listobject->querystring .= "   select * from sources where ";
      $listobject->querystring .= "   projectid = $projectid ";
      $listobject->performQuery();

      $listobject->querystring = "create temp table worksourcetype as ";
      $listobject->querystring .= "   select * from sourceloadtype where ";
      $listobject->querystring .= "   projectid = $projectid ";
      $listobject->performQuery();

      # create a subshed population table, for the selected year
      # if this year is not an exact year, use the numerical mean of bounding years
      # if the selected year is outside of the date range, for one or more
      # sources, use the closest year


      print("&nbsp;&nbsp;&nbsp;&nbsp; Copying Source Population Table <br>");
      $listobject->querystring = "create temp table copysubsheds as ";
      $listobject->querystring .= "   select $subshedcolumns from subshed where ";
      $listobject->querystring .= "   projectid = $projectid ";
      $listobject->querystring .= "   $ssc ";
      $listobject->performQuery();
      popInterp($listobject, $projectid, $thisyear, 'copysubsheds', $debug);


       $listobject->debug = $prevdebug;

   }

   function makeMonProduction($listobject, $projectid, $overwrite, $debug) {

      # create a general table pulling together the characteristics
      # of the various loads by subwatershed
      # this table unites the worksourcetype table with theworksourcestable
      # including the source population, source production per AU/day

       if ( !($listobject->tableExists('worksublu')) ) {
          print("<b>Error:</b>Table working tables do not exist. makeTempWorkTables must be called before this function. Will not continue.<br>");
          die;
       }

      if ($listobject->tableExists('monsubproduction') and !$overwrite) {
         print("<b>Warning:</b>Table monsubproduction already exists. Will not overwrite<br>");
         return;
      }

      $listobject->querystring = "create temp table monsubproduction as select a.sourceid, a.avgweight, a.sourcename, a.distrotype, b.subshedid, b.sourcepop as popdens, b.sourcepop as actualpop, c.pollutantprod, c.produnits, c.conv, c.auweight, c.typeid, c.sourceclass, c.starttime, c.duration, (b.sourcepop * a.avgweight / c.auweight) as aucount,  1.0 as meanpopfact, ";
      $listobject->querystring .= "0.0 as  annualproduction, ";
      $listobject->querystring .= "    1.0 as JAN, 1.0 as FEB, 1.0 as MAR, 1.0 as APR,";
      $listobject->querystring .= "    1.0 as MAY, 1.0 as JUN, 1.0 as JUL, 1.0 as AUG,";
      $listobject->querystring .= "    1.0 as SEP, 1.0 as OCT, 1.0 as NOV, 1.0 as DEC";
      $listobject->querystring .= "    from worksources as a,";
      $listobject->querystring .= "         worksubshed as b,";
      $listobject->querystring .= "         worksourcetype as c";
      $listobject->querystring .= "    where ";
      $listobject->querystring .= "        a.distrotype not in (10)";
      $listobject->querystring .= "    and b.sourceid = a.sourceid";
      $listobject->querystring .= "    and c.typeid = a.typeid";

      if ($debug == 1) {
         print("$listobject->querystring ; <br>");
      }

      $listobject->performQuery();

      $listobject->querystring = "update monsubproduction set ";
      $listobject->querystring .= " JAN = (a.popdens * b.JAN * a.conv * a.pollutantprod * (a.avgweight / a.auweight) ), ";
      $listobject->querystring .= " FEB = (a.popdens * b.FEB * a.conv * a.pollutantprod * (a.avgweight / a.auweight) ),";
      $listobject->querystring .= " MAR = (a.popdens * b.MAR * a.conv * a.pollutantprod * (a.avgweight / a.auweight) ),";
      $listobject->querystring .= " APR = (a.popdens * b.APR * a.conv * a.pollutantprod * (a.avgweight / a.auweight) ),";
      $listobject->querystring .= " MAY = (a.popdens * b.MAY * a.conv * a.pollutantprod * (a.avgweight / a.auweight) ),";
      $listobject->querystring .= " JUN = (a.popdens * b.JUN * a.conv * a.pollutantprod * (a.avgweight / a.auweight) ),";
      $listobject->querystring .= " JUL = (a.popdens * b.JUL * a.conv * a.pollutantprod * (a.avgweight / a.auweight) ),";
      $listobject->querystring .= " AUG = (a.popdens * b.AUG * a.conv * a.pollutantprod * (a.avgweight / a.auweight) ),";
      $listobject->querystring .= " SEP = (a.popdens * b.SEP * a.conv * a.pollutantprod * (a.avgweight / a.auweight) ),";
      $listobject->querystring .= " OCT = (a.popdens * b.OCT * a.conv * a.pollutantprod * (a.avgweight / a.auweight) ),";
      $listobject->querystring .= " NOV = (a.popdens * b.NOV * a.conv * a.pollutantprod * (a.avgweight / a.auweight) ),";
      $listobject->querystring .= " DEC = (a.popdens * b.DEC * a.conv * a.pollutantprod * (a.avgweight / a.auweight) )";
      $listobject->querystring .= "   from monsubproduction as a,";
      $listobject->querystring .= "   workdistro as b";
      $listobject->querystring .= "   where a.sourceid = b.sourceid and";
      $listobject->querystring .= "         monsubproduction.sourceid = a.sourceid and";
      $listobject->querystring .= "         monsubproduction.subshedid = a.subshedid and";
      $listobject->querystring .= "         monsubproduction.subshedid = b.subshedid and";
      # monthly population fluctuation is spreadid 3
      $listobject->querystring .= "         b.spreadid = 3";
      $listobject->performQuery();

      if ($debug == 1) {
         print("$listobject->querystring ; <br>");
      }

      $listobject->querystring = "update monsubproduction set ";
      $listobject->querystring .= "meanpopfact = ((b.JAN + b.FEB + b.MAR + b.APR ";
      $listobject->querystring .= " + b.MAY + b.JUN + b.JUL + b.AUG + b.SEP + b.OCT ";
      $listobject->querystring .= "+ b.NOV + b.DEC ) / 12.0)  ";
      $listobject->querystring .= "from workdistro as b ";
      $listobject->querystring .= "where b.sourceid = monsubproduction.sourceid ";
      $listobject->querystring .= "   and monsubproduction.subshedid = b.subshedid ";
      $listobject->querystring .= "   and b.spreadid = 3";
      $listobject->performQuery();

      if ($debug == 1) {
         print("$listobject->querystring ; <br>");
      }

      $listobject->querystring = "update monsubproduction set ";
      $listobject->querystring .= "   actualpop = meanpopfact * popdens";
      $listobject->performQuery();

      if ($debug == 1) {
         print("$listobject->querystring ; <br>");
      }

      $listobject->querystring = "update monsubproduction set ";
      $listobject->querystring .= " annualproduction = (b.JAN*a.JAN + b.FEB*a.FEB ";
      $listobject->querystring .= " + b.MAR*a.MAR  + b.APR*a.APR + b.MAY*a.MAY ";
      $listobject->querystring .= " + b.JUN*a.JUN  + b.JUL*a.JUL + b.AUG*a.AUG";
      $listobject->querystring .= " + b.SEP*a.SEP  + b.OCT*a.OCT + b.NOV*a.NOV ";
      $listobject->querystring .= " + b.DEC*a.DEC ) ";
      $listobject->querystring .= " from monthdays as b, ";
      $listobject->querystring .= "     monsubproduction as a ";
      $listobject->querystring .= " where monsubproduction.sourceid = a.sourceid ";
      $listobject->querystring .= "    and monsubproduction.subshedid = a.subshedid ";
      $listobject->performQuery();

      if ($debug == 1) {
         print("$listobject->querystring ; <br>");
      }

      $listobject->querystring = "select * from monsubproduction order by subshedid, sourcename";
      $listobject->performQuery();
      if ($debug == 1) {
         $listobject->showList();
      }

   }


   function makePollutantProd($listobject, $projectid, $overwrite, $debug) {

      # create a general table pulling together the characteristics
      # of the various loads by subwatershed
      # this table unites the worksourcetype table with theworksourcestable
      # including the source population, source production in units of mass per day

      if ($listobject->tableExists('sourcepollprod') and !$overwrite) {
         print("<b>Warning:</b>Table sourcepollprod already exists. Will not overwrite<br>");
         return;
      }
      if ( !($listobject->tableExists('monsubproduction')) ) {
         makeMonProduction($listobject, $projectid, $overwrite, $debug);
      }


      $listobject->querystring = "create temp table sourcepollprod as select c.sourceid,";
      $listobject->querystring .= "c.sourcename, a.sourcetypeid, a.pollutanttype, a.typeid, a.pollutantconc, ";
      $listobject->querystring .= "a.conv, a.convunits, b.actualpop, b.aucount, b.sourceclass, ";
      $listobject->querystring .= "a.volatilization, a.storagedieoff, b.annualproduction, ";
      $listobject->querystring .= "a.pollutantname, b.subshedid, b.produnits, a.concunits, ";
      $listobject->querystring .= "   (b.JAN * d.JAN + b.FEB * d.FEB + b.MAR * d.MAR ";
      $listobject->querystring .= "   + b.APR * d.APR + b.MAY * d.MAY + b.JUN * d.JUN ";
      $listobject->querystring .= "   + b.JUL * d.JUL + b.AUG * d.AUG + b.SEP * d.SEP ";
      $listobject->querystring .= "   + b.OCT * d.OCT + b.NOV * d.NOV + b.DEC * d.DEC ) ";
      $listobject->querystring .= " * a.pollutantconc * a.conv as annualpollutant, ";
      $listobject->querystring .= "b.JAN * a.pollutantconc * a.conv as JAN, ";
      $listobject->querystring .= "b.FEB * a.pollutantconc * a.conv as FEB, ";
      $listobject->querystring .= "b.MAR * a.pollutantconc * a.conv as MAR, ";
      $listobject->querystring .= "b.APR * a.pollutantconc * a.conv as APR,";
      $listobject->querystring .= "b.MAY * a.pollutantconc * a.conv as MAY, ";
      $listobject->querystring .= "b.JUN * a.pollutantconc * a.conv as JUN, ";
      $listobject->querystring .= "b.JUL * a.pollutantconc * a.conv as JUL, ";
      $listobject->querystring .= "b.AUG * a.pollutantconc * a.conv as AUG, ";
      $listobject->querystring .= "b.SEP * a.pollutantconc * a.conv as SEP, ";
      $listobject->querystring .= "b.OCT * a.pollutantconc * a.conv as OCT, ";
      $listobject->querystring .= "b.NOV * a.pollutantconc * a.conv as NOV, ";
      $listobject->querystring .= "b.DEC * a.pollutantconc * a.conv as DEC";
      $listobject->querystring .= "    from worksourcepolls as a,";
      $listobject->querystring .= "         monsubproduction as b,";
      $listobject->querystring .= "         worksources as c, monthdays as d ";
      $listobject->querystring .= "    where ";
      $listobject->querystring .= "        b.sourceid = c.sourceid";
      $listobject->querystring .= "    and c.typeid = a.sourcetypeid";
      $listobject->performQuery();

      if ($debug == 1) {
         print("$listobject->querystring ; <br>");
      }


      $listobject->querystring = "select * from sourcepollprod order by subshedid, pollutantname";
      #$listobject->performQuery();
      if ($debug == 1) {
         #$listobject->showList();
      }

   }

   function makeMonApplied($listobject, $projectid, $overwrite, $debug) {

      # creates a table of all daily load production that goes to
      # directly to a destination landuse (spreadid = 1)
      # this does not include the storage landuse, however, the following routine
      # makeMonStorageApplied will perform the divvying up of stored loads onto
      # recipient worklanduses.
      if ($listobject->tableExists('monapplied') and !$overwrite) {
         print("<b>Warning:</b>Table monapplied already exists. Will not overwrite<br>");
         return;
      }
      if ( !($listobject->tableExists('sourcepollprod')) ) {
         makePollutantProd($listobject, $projectid, $overwrite, $debug);
      }


      $listobject->querystring = "create temp table monapplied (subshedid varchar(32), ";
      $listobject->querystring .= " landuseid integer, luname varchar(12), sourceid integer, sourceclass integer, ";
      $listobject->querystring .= " actualpop float8, sourcetypeid integer, pollutanttype integer, typeid integer, ";
      $listobject->querystring .= " volatilization float8, storagedieoff float8, annualproduction float8, ";
      $listobject->querystring .= " annualpollutant float8, spreadid integer, ";
      $listobject->querystring .= " JAN float8, ";
      $listobject->querystring .= " FEB float8, ";
      $listobject->querystring .= " MAR float8, ";
      $listobject->querystring .= " APR float8,";
      $listobject->querystring .= " MAY float8, ";
      $listobject->querystring .= " JUN float8, ";
      $listobject->querystring .= " JUL float8, ";
      $listobject->querystring .= " AUG float8, ";
      $listobject->querystring .= " SEP float8, ";
      $listobject->querystring .= " OCT float8, ";
      $listobject->querystring .= " NOV float8, ";
      $listobject->querystring .= " DEC float8 ) ";
      $listobject->performQuery();

      if ($debug) {
         print("$listobject->querystring ; <br>");
      }

      $listobject->querystring = " insert into monapplied select a.subshedid, ";
      $listobject->querystring .= "b.landuseid, c.hspflu as luname, a.sourceid, a.sourceclass, ";
      $listobject->querystring .= " a.actualpop,a.sourcetypeid, a.pollutanttype, a.typeid, ";
      $listobject->querystring .= "a.volatilization, a.storagedieoff, a.annualproduction, ";
      $listobject->querystring .= "a.annualpollutant, b.spreadid, ";
      $listobject->querystring .= "b.JAN * a.JAN as JAN, ";
      $listobject->querystring .= "b.FEB * a.FEB as FEB, ";
      $listobject->querystring .= "b.MAR * a.MAR as MAR, ";
      $listobject->querystring .= "b.APR * a.APR as APR,";
      $listobject->querystring .= "b.MAY * a.MAY as MAY, ";
      $listobject->querystring .= "b.JUN * a.JUN as JUN, ";
      $listobject->querystring .= "b.JUL * a.JUL as JUL, ";
      $listobject->querystring .= "b.AUG * a.AUG as AUG, ";
      $listobject->querystring .= "b.SEP * a.SEP as SEP, ";
      $listobject->querystring .= "b.OCT * a.OCT as OCT, ";
      $listobject->querystring .= "b.NOV * a.NOV as NOV, ";
      $listobject->querystring .= "b.DEC * a.DEC as DEC";
      $listobject->querystring .= "    from sourcepollprod as a,";
      $listobject->querystring .= "         workdistro as b, worklanduses as c ";
      $listobject->querystring .= "    where b.sourceid = a.sourceid";
      $listobject->querystring .= "    and b.subshedid = a.subshedid";
      $listobject->querystring .= "    and b.spreadid = 1";
      $listobject->querystring .= "    and b.landuseid = c.luid";
      $listobject->performQuery();

      if ($debug) {
         print("$listobject->querystring ; <br>");
         /*
         $listobject->querystring = "select * from monapplied";
         $listobject->performQuery();
         $listobject->showList();
         */
      }

   }

    function makeMonStored($listobject, $projectid, $overwrite, $debug) {

       # creates a table of all daily load production that goes to a destination landuse
       # this includes everything but the storage landuse which goes into a separate
       # routine.
       if ($listobject->tableExists('annualstored') and !$overwrite) {
          print("<b>Warning:</b>Table annualstored already exists. Will not overwrite<br>");
          return;
       }
       if ( !($listobject->tableExists('monapplied')) ) {
          makeMonApplied($listobject, $projectid, $overwrite, $debug);
       }

       $prevdebug = $listobject->debug;
       $listobject->debug = $debug;

       $listobject->querystring = "create temp table annualstored as select a.subshedid, ";
       $listobject->querystring .= "a.landuseid, a.sourceid, a.sourceclass, ";
       $listobject->querystring .= "a.volatilization, a.storagedieoff, ";
       $listobject->querystring .= "a.sourcetypeid, a.pollutanttype, a.typeid, ";
       $listobject->querystring .= " a.annualproduction, 0.0 as vconst, ";
       $listobject->querystring .= "(b.JAN*a.JAN + b.FEB*a.FEB + b.MAR*a.MAR ";
       $listobject->querystring .= " + b.APR*a.APR + b.MAY*a.MAY + b.JUN*a.JUN ";
       $listobject->querystring .= " + b.JUL*a.JUL + b.AUG*a.AUG + b.SEP*a.SEP ";
       $listobject->querystring .= " + b.OCT*a.OCT + b.NOV*a.NOV + b.DEC*a.DEC ) as annualstored, ";
       $listobject->querystring .= "0.0 as annualdieoff, ";
       $listobject->querystring .= "0.0 as annualvolatilized, ";
       $listobject->querystring .= " 0.0 as annualapplied";
       $listobject->querystring .= "    from monapplied as a,";
       $listobject->querystring .= "       monthdays as b";
       $listobject->querystring .= "    where ";
       $listobject->querystring .= "        a.landuseid in (select luid from worklanduses where ";
       $listobject->querystring .= "           landuseid = 10)";
       $listobject->querystring .= "       and b.spreadid = 4";
       $listobject->performQuery();


       $listobject->querystring = "update annualstored set ";
       $listobject->querystring .= " annualdieoff = (1.0 - storagedieoff) * annualstored, ";
       $listobject->querystring .= " annualvolatilized = (1.0 - volatilization) * annualstored ";
       $listobject->performQuery();


       $listobject->querystring = "update annualstored ";
       $listobject->querystring .= "set annualapplied = annualstored - (annualdieoff + annualvolatilized)";
       $listobject->performQuery();

       # created 'vconst' - a 'virtual concentration' for this pollutant, after all losses
       # this virtual concentration will be used later to back calculate remaining
       # amount after applying to nutrient management acres
       $listobject->querystring = "update annualstored ";
       $listobject->querystring .= "set vconst = (annualapplied / annualproduction)";
       $listobject->querystring .= "   where annualproduction > 0";
       $listobject->performQuery();

       $listobject->debug = $prevdebug;

   }

    function makeGenericStored($listobject, $projectid, $basename, $spreadid, $calclosses, $overwrite, $debug) {

       # creates a table of all daily load production that goes to the destination landuse
       # specified by this spreadid

       # $calclosses - flag to calculate losses due to volatilization or dieoff 0 or 1

       $tname = $basename . "_stored";

       if ($listobject->tableExists($tname) ) {
          if (! $overwrite) {
             print("<b>Warning:</b>Table $tname already exists. Will not overwrite<br>");
             return;
          } else {
             $listobject->querystring = "drop table $tname";
             $listobject->performQuery();
             $listobject->querystring = "drop table $sname";
             $listobject->performQuery();
          }
       }
       if ( !($listobject->tableExists('monapplied')) ) {
          makeMonApplied($listobject, $projectid, $overwrite, $debug);
       } else {
         # print("monapplied exists <BR>");
       }

       $prevdebug = $listobject->debug;
       $listobject->debug = $debug;

       $listobject->querystring = "select * from map_generic_distro where ";
       $listobject->querystring .= "spreadid = $spreadid and projectid = $projectid ";
       $listobject->performQuery();
       $storage_lu = $listobject->getRecordValue(1,'landuseid');

       #print("Storage landuse ID: $storage_lu <br>");

       $listobject->querystring = "create temp table $tname as select a.subshedid, ";
       $listobject->querystring .= "a.landuseid, a.sourceid, a.sourceclass, a.spreadid, ";
       $listobject->querystring .= "a.volatilization, a.storagedieoff, ";
       $listobject->querystring .= "a.sourcetypeid, a.pollutanttype, a.typeid, ";
       $listobject->querystring .= " a.annualproduction, 0.0 as vconst, ";
       $listobject->querystring .= "(b.JAN*a.JAN + b.FEB*a.FEB + b.MAR*a.MAR ";
       $listobject->querystring .= " + b.APR*a.APR + b.MAY*a.MAY + b.JUN*a.JUN ";
       $listobject->querystring .= " + b.JUL*a.JUL + b.AUG*a.AUG + b.SEP*a.SEP ";
       $listobject->querystring .= " + b.OCT*a.OCT + b.NOV*a.NOV + b.DEC*a.DEC ) as annualstored, ";
       $listobject->querystring .= "    b.JAN*a.JAN as JAN, ";
       $listobject->querystring .= "    b.FEB*a.FEB as FEB, ";
       $listobject->querystring .= "    b.MAR*a.MAR as MAR, ";
       $listobject->querystring .= "    b.APR*a.APR as APR, ";
       $listobject->querystring .= "    b.MAY*a.MAY as MAY, ";
       $listobject->querystring .= "    b.JUN*a.JUN as JUN, ";
       $listobject->querystring .= "    b.JUL*a.JUL as JUL, ";
       $listobject->querystring .= "    b.AUG*a.AUG as AUG, ";
       $listobject->querystring .= "    b.SEP*a.SEP as SEP, ";
       $listobject->querystring .= "    b.OCT*a.OCT as OCT, ";
       $listobject->querystring .= "    b.NOV*a.NOV as NOV, ";
       $listobject->querystring .= "    b.DEC*a.DEC as DEC, ";
       $listobject->querystring .= "0.0 as annualdieoff, ";
       $listobject->querystring .= "0.0 as annualvolatilized, ";
       $listobject->querystring .= " 0.0 as annualapplied";
       $listobject->querystring .= "    from monapplied as a,";
       $listobject->querystring .= "       monthdays as b";
       $listobject->querystring .= "    where ";
       $listobject->querystring .= "        a.landuseid in (select luid from worklanduses where ";
       $listobject->querystring .= "           landuseid = $storage_lu)";
       $listobject->querystring .= "       and b.spreadid = 4 ";
       $listobject->performQuery();


       if ($calclosses) {
          # this allows us to switch volatilization and dieoff losses on and off.
          # this is useful for "virtual storage bins" such as the pasture virtual storage.
          # where volatilization should be off (since we are simulating daily as-excreted, but using
          # the storage methodology to make it more realistic/flexible), but for regular ag waste
          # storage, we WANT to simulate volatilization and attenuation (dieoff)

          $listobject->querystring = "update $tname set ";
          $listobject->querystring .= " annualdieoff = (1.0 - storagedieoff) * annualstored, ";
          $listobject->querystring .= " annualvolatilized = (1.0 - volatilization) * annualstored ";
          $listobject->performQuery();
       }


       $listobject->querystring = "update $tname ";
       $listobject->querystring .= "set annualapplied = annualstored - (annualdieoff + annualvolatilized)";
       $listobject->performQuery();

       # created 'vconst' - a 'virtual concentration' for this pollutant, after all losses
       # this virtual concentration will be used later to back calculate remaining
       # amount after applying to nutrient management acres
       $listobject->querystring = "update $tname ";
       $listobject->querystring .= "set vconst = (annualapplied / annualproduction)";
       $listobject->querystring .= "   where annualproduction > 0";
       $listobject->performQuery();

       $listobject->debug = $prevdebug;
       #print("$listobject->querystring ; <br>");

       return $tname;

   }

   function allLoadsSummarized($listobject, $projectid, $overwrite, $debug, $thisyear=1982, $scenarioid=1, $subsheds='') {

       # creates a table of all daily load production that goes to a destination landuse
       # this includes everything but the storge landuse which goes into a separate
       # routine.
       if ($listobject->tableExists('all_loads') and !$overwrite) {
          print("<b>Warning:</b>Table all_loads already exists. Will not overwrite<br>");
          return;
       } else {
          if ($listobject->tableExists('all_loads')) {
             $listobject->querystring = "drop table all_loads ";
             $listobject->performQuery();
          }
       }

       if (strlen($subsheds) > 0) {
         # this expression was only necessary when the subshedid was a string
         # now it is integer, so we don;t need to convert and can pass
         # $subsheds directly into the query
         # this was slowing the queries down substantially since they
         # were forced to
         $subshedlist = "'" . join("','", explode(',', $subsheds)) . "'";
         $ssc = " and a.subshedid in ($subshedlist)";
      } else {
         $ssc = '';
      }

       $listobject->querystring = "create temp table all_loads as select a.subshedid, a.thisyear, ";
       $listobject->querystring .= "a.sourceid, a.sourceclass, a.volatilization, a.storagedieoff, ";
       $listobject->querystring .= "a.sourcetypeid, a.pollutanttype, a.typeid, 0.0 as totalpop, ";
       $listobject->querystring .= " a.annualproduction, 0.0 as vconst, ";
       $listobject->querystring .= "(b.JAN*a.JAN + b.FEB*a.FEB + b.MAR*a.MAR ";
       $listobject->querystring .= " + b.APR*a.APR + b.MAY*a.MAY + b.JUN*a.JUN ";
       $listobject->querystring .= " + b.JUL*a.JUL + b.AUG*a.AUG + b.SEP*a.SEP ";
       $listobject->querystring .= " + b.OCT*a.OCT + b.NOV*a.NOV + b.DEC*a.DEC ) as annualproduced, ";
       $listobject->querystring .= "  0.0 as annualvolatilized, 0.0 as annualdieoff, 0.0 as annualapplied";
       $listobject->querystring .= "    from scen_sourcepollprod as a,";
       $listobject->querystring .= "       monthdays as b";
       $listobject->querystring .= "    where a.scenarioid = $scenarioid ";
       $listobject->querystring .= "       and a.thisyear = $thisyear ";
       $listobject->querystring .= "       and b.spreadid = 4";
       $listobject->querystring .= "       $ssc ";
       if ($debug) {
          print("$listobject->querystring ; <br>");
       }
       $listobject->performQuery();

       $listobject->querystring = "update all_loads ";
       $listobject->querystring .= "set annualdieoff = (1.0 - storagedieoff) * annualproduced, ";
       $listobject->querystring .= " annualvolatilized = (1.0 - volatilization) * annualproduced ";
       if ($debug) {
          print("$listobject->querystring ; <br>");
       }
       $listobject->performQuery();


       $listobject->querystring = "update all_loads ";
       $listobject->querystring .= "set annualapplied = annualproduced - (annualdieoff + annualvolatilized)";
       if ($debug) {
          print("$listobject->querystring ; <br>");
       }
       $listobject->performQuery();


       $listobject->querystring = "update all_loads ";
       $listobject->querystring .= "set totalpop = scen_monsubproduction.actualpop ";
       $listobject->querystring .= " from scen_monsubproduction ";
       $listobject->querystring .= " where all_loads.subshedid = scen_monsubproduction.subshedid ";
       $listobject->querystring .= "    and all_loads.sourceid = scen_monsubproduction.sourceid ";
       $listobject->querystring .= "    and scen_monsubproduction.thisyear = $thisyear ";
       $listobject->querystring .= "    and scen_monsubproduction.scenarioid = $scenarioid ";
       if ($debug) {
          print("$listobject->querystring ; <br>");
       }
       $listobject->performQuery();

    }


    function makeSubShedStored($listobject, $projectid, $overwrite, $debug) {

       # creates a table of all daily load production that goes to a destination landuse
       # this includes everything but the storge landuse which goes into a separate
       # routine.
       if ($listobject->tableExists('subshedstored') and !$overwrite) {
          print("<b>Warning:</b>Table subshedstored already exists. Will not overwrite<br>");
          return;
       }
       if ( !($listobject->tableExists('annualstored')) ) {
          makeMonStored($listobject, $projectid, $overwrite, $debug);
       }

       $prevdebug = $listobject->debug;
       $listobject->debug = $debug;

       # sum up 'annualapplied' column because this represents total available for application
       # after all losses are considered.
       $listobject->querystring = "create temp table subshedstored as select subshedid, ";
       $listobject->querystring .= "sum(annualapplied) as totalstored, pollutanttype ";
       $listobject->querystring .= "    from annualstored";
       $listobject->querystring .= "    group by subshedid, pollutanttype";
       $listobject->performQuery();

       $listobject->debug = $prevdebug;

   }


    function makeWACTable($listobject, $projectid, $overwrite, $debug) {

       # creates a table of all daily load production that goes to a destination landuse
       # this includes everything but the storge landuse which goes into a separate
       # routine.
       if ($listobject->tableExists('totalnmwactable') and !$overwrite) {
          print("<b>Warning:</b>Table totalnmwactable already exists. Will not overwrite<br>");
          return;
       }
       if ( !($listobject->tableExists('nm_sublu')) ) {
          print("<b>Error:</b>Table wokring tables do not exist. makeTempWorkTables must be called before this function. Will not continue.<br>");
          die;
       }

       $prevdebug = $listobject->debug;
       $listobject->debug = $debug;

       # creates Waste Assimilative Capacity table for nutrient managed acres
       # by grabbing the nitrogen plan based acres first
       $listobject->querystring = "create temp table sublunmwactable as select a.subshedid, ";
       $listobject->querystring .= "a.sublu, a.luname, b.planduseid as landuseid, a.nm_planbase as pollutanttype, ";
       $listobject->querystring .= "a.luarea * a.maxn as pollcapacity ";
       $listobject->querystring .= "    from nm_sublu as a, ";
       $listobject->querystring .= "       worklanduses as b ";
       $listobject->querystring .= "    where a.luname = b.hspflu ";
       $listobject->querystring .= "       and a.nm_planbase = 1 ";
       #$listobject->querystring .= "       and a.luarea > 0 ";
       $listobject->performQuery();

       # creates Waste Assimilative Capacity table for non-nutrient managed acres
       # assumes that the avaialble wastes will be spread proportional to the
       # given landuses estimated nitrogen demand.
       $listobject->querystring = "create temp table sublucnwactable as select a.subshedid, ";
       $listobject->querystring .= "a.sublu, a.luname, a.luarea, a.maxn, ";
       $listobject->querystring .= "b.planduseid as landuseid, 1 as pollutanttype, ";
       $listobject->querystring .= "a.luarea * a.maxn as pollcapacity ";
       $listobject->querystring .= "    from worksublu as a, ";
       $listobject->querystring .= "       worklanduses as b, workdistro as c ";
       $listobject->querystring .= "    where a.luname = b.hspflu";
       $listobject->querystring .= "       and a.luarea > 0 ";
       $listobject->querystring .= "       and b.landuseid = c.landuseid ";
       $listobject->querystring .= "       and a.subshedid = c.subshedid ";
       $listobject->querystring .= "       and c.spreadid = 6 ";
       $listobject->querystring .= "       and (a.sublu not in (select sublu from nm_sublu))";
       $listobject->performQuery();

       # adds phosphorous plan based  acres into Waste Assimilative Capacity table
       # for nutrient managed acres
       $listobject->querystring = "insert into sublunmwactable (subshedid, sublu, luname, ";
       $listobject->querystring .= "landuseid, pollutanttype, pollcapacity ) select a.subshedid, ";
       $listobject->querystring .= "a.sublu, a.luname, b.planduseid as landuseid, a.nm_planbase, ";
       $listobject->querystring .= "a.luarea * a.maxp as pollcapacity ";
       $listobject->querystring .= "    from nm_sublu as a, ";
       $listobject->querystring .= "       worklanduses as b ";
       $listobject->querystring .= "    where a.luname = b.hspflu ";
       $listobject->querystring .= "       and a.nm_planbase = 2 ";
       $listobject->performQuery();


       # total up all nutrient management plan acre capacities for calculating ratios
       $listobject->querystring = "create temp table totalnmwactable as select subshedid, ";
       $listobject->querystring .= "pollutanttype, sum(pollcapacity) as pollcapacity ";
       $listobject->querystring .= "    from sublunmwactable as a";
       $listobject->querystring .= "    group by subshedid, pollutanttype";
       $listobject->performQuery();


       # total up all non-nutrient management plan acre capacities for calculating ratios
       $listobject->querystring = "create temp table totalcnwactable as select subshedid, ";
       $listobject->querystring .= " pollutanttype, sum(pollcapacity) as pollcapacity ";
       $listobject->querystring .= "    from sublucnwactable as a";
       $listobject->querystring .= "    group by subshedid, pollutanttype";
       $listobject->performQuery();

       $listobject->debug = $prevdebug;

   }

   function createRemainingCapacity2($listobject, $projectid, $basename, $totaltable, $captable, $lutable, $overwrite, $debug) {
      # creates a table of the nutrient assimilative capacity remaining on each landuse
      # in the input table, $captable and land use table $lutable
      $remcap = "$basename" . "_remcap";
      if ($listobject->tableExists("$remcap") ) {
         if (!$overwrite) {
            print("<b>Warning:</b>Table $basename_remcap already exists. Will not overwrite<br>");
            return;
         } else {
            $listobject->querystring = "drop table $remcap ";
            $listobject->performQuery();
         }
      }

      # create blank table to start
      $listobject->querystring = " create temp table $remcap ( subshedid varchar(32), ";
      $listobject->querystring .= "   sublu integer, luname varchar(12), luarea float8, ";
      $listobject->querystring .= "   annualapplied float8, landuseid integer, ";
      $listobject->querystring .= "   pollutanttype integer, ";
      $listobject->querystring .= "   deficit float8, ";
      $listobject->querystring .= "   pollcapacity float8, ";
      $listobject->querystring .= "   defmax float8, ";
      $listobject->querystring .= "   pollmax float8 ";
      $listobject->querystring .= " ) ";
      if ($debug) { print("$listobject->querystring ; <br>"); }
      $listobject->performQuery();


      # repeat for each possible limiting constituent in the capacity table
      $listobject->querystring = "  select b.typeid as nm_planbase, b.master_constit ";
      $listobject->querystring .= " from pollutanttype as b ";
      $listobject->querystring .= " group by b.typeid, b.master_constit ";
      if ($debug) { print("$listobject->querystring ; <br>"); }
      $listobject->performQuery();

      $theseplans = $listobject->queryrecords;

      foreach ($theseplans as $thisplan) {
         # reset optcol so we know if we have a constituent match
         $optcol = '';
         $limconstit = $thisplan['nm_planbase'];
         $master_constit = $thisplan['master_constit'];
         switch($master_constit) {
            case 1:
               $optcol = 'optn';
               $maxcol = 'maxn';
            break;

            case 2:
               $optcol = 'optp';
               $maxcol = 'maxp';
            break;

         }

         if ($optcol <> '') {
            # make sure that we have a match on a column that contains information about our poll
            if ($totaltable <> '') {

               # total table exists, therefore use it to create the remcap table
               # insert records for existing nitrogen applications
               $listobject->querystring = "insert into $remcap (subshedid, sublu, luname, luarea, ";
               $listobject->querystring .= "    annualapplied, landuseid, pollutanttype, ";
               $listobject->querystring .= "    deficit, pollcapacity, defmax, pollmax) select a.subshedid, ";
               $listobject->querystring .= "   a.sublu, b.luname, a.luarea, a.annualapplied, ";
               $listobject->querystring .= "   c.planduseid as landuseid, a.pollutanttype, ";
               $listobject->querystring .= "   (b.optn - a.annualapplied) as deficit, ";
               $listobject->querystring .= "   a.luarea *(b.$optcol - a.annualapplied) as pollcapacity, ";
               $listobject->querystring .= "   (b.maxn - a.annualapplied) as defmax, ";
               $listobject->querystring .= "   a.luarea *(b.$maxcol - a.annualapplied) as pollmax ";
               $listobject->querystring .= " from $totaltable as a, $captable as b, ";
               $listobject->querystring .= "    $lutable as c ";
               $listobject->querystring .= " where a.sublu = b.sublu and a.pollutanttype = $limconstit ";
               $listobject->querystring .= "    and b.luname = c.hspflu";
               if ($debug) { print("$listobject->querystring ; <br>"); }
               $listobject->performQuery();

            }

            # insert blank entries for this limconstit
            $listobject->querystring = "insert into $remcap (subshedid, sublu, luname, luarea, ";
            $listobject->querystring .= "    annualapplied, landuseid, pollutanttype, ";
            $listobject->querystring .= "    deficit, pollcapacity, defmax, pollmax) select b.subshedid, ";
            $listobject->querystring .= "    b.sublu, b.luname, b.luarea, 0, ";
            $listobject->querystring .= "    c.planduseid as landuseid, $limconstit, ";
            $listobject->querystring .= "   b.optn, ";
            $listobject->querystring .= "    b.luarea*b.$optcol as pollcapacity, ";
            $listobject->querystring .= "   b.maxn, ";
            $listobject->querystring .= "    b.luarea*b.$maxcol as pollmax ";
            $listobject->querystring .= " from $captable as b, ";
            $listobject->querystring .= "    $lutable as c ";
            $listobject->querystring .= " where b.sublu not in ";
            $listobject->querystring .= " (select sublu from $remcap where pollutanttype = $limconstit)";
            $listobject->querystring .= "    and b.luname = c.hspflu";
      #         print("$listobject->querystring ; <br>");
            $listobject->performQuery();

         }

      }

      return $remcap;

   }

   function createRemainingCapacity($listobject, $projectid, $basename, $totaltable, $captable, $lutable, $overwrite, $debug) {
      # creates a table of the nutrient assimilative capacity remaining on each landuse
      # in the input table, $captable and land use table $lutable
      $remcap = "$basename" . "_remcap";
      if ($listobject->tableExists("$remcap") ) {
         if (!$overwrite) {
            print("<b>Warning:</b>Table $basename_remcap already exists. Will not overwrite<br>");
            return;
         } else {
            $listobject->querystring = "drop table $remcap ";
            $listobject->performQuery();
         }
      }

      if ($totaltable <> '') {
         # total table exists, therefore create from already applied
         $listobject->querystring = "create temp table $remcap as select a.subshedid, ";
         $listobject->querystring .= "   a.sublu, b.luname, a.luarea, a.annualapplied, ";
         $listobject->querystring .= "   c.planduseid as landuseid, a.pollutanttype, ";
         $listobject->querystring .= "   (b.optn - a.annualapplied) as deficit, ";
         $listobject->querystring .= "   a.luarea *(b.optn - a.annualapplied) as pollcapacity, ";;
         $listobject->querystring .= "   (b.maxn - a.annualapplied) as defmax, ";
         $listobject->querystring .= "   a.luarea *(b.maxn - a.annualapplied) as pollmax ";
         $listobject->querystring .= " from $totaltable as a, $captable as b, ";
         $listobject->querystring .= "    $lutable as c ";
         $listobject->querystring .= " where a.sublu = b.sublu and a.pollutanttype = 1 ";
         $listobject->querystring .= "    and b.luname = c.hspflu";
#         print("$listobject->querystring ; <br>");
         $listobject->performQuery();


         $listobject->querystring = "insert into $remcap (subshedid, sublu, luname, luarea, ";
         $listobject->querystring .= "    annualapplied, landuseid, pollutanttype, ";
         $listobject->querystring .= "    deficit, pollcapacity, defmax, pollmax) select a.subshedid, ";
         $listobject->querystring .= "    a.sublu, b.luname, a.luarea, a.annualapplied, ";
         $listobject->querystring .= "    c.planduseid, a.pollutanttype, ";
         $listobject->querystring .= "   (b.optp - a.annualapplied), ";
         $listobject->querystring .= "    a.luarea*(b.optp - a.annualapplied) as pollcapacity, ";
         $listobject->querystring .= "   (b.maxp - a.annualapplied), ";
         $listobject->querystring .= "    a.luarea*(b.maxp - a.annualapplied) as pollmax ";
         $listobject->querystring .= " from $totaltable as a, $captable as b, ";
         $listobject->querystring .= "    $lutable as c ";
         $listobject->querystring .= " where a.sublu = b.sublu and a.pollutanttype = 2 ";
         $listobject->querystring .= "    and b.luname = c.hspflu";
#         print("$listobject->querystring ; <br>");
         $listobject->performQuery();


         # now, insert zero values for any landuses that have not already received
         # an application. This manually grabs pollutant types 1 and 2,
         # but should be modified to later bring in any number of
         # pollutanttypes
         $listobject->querystring = "insert into $remcap (subshedid, sublu, luname, luarea, ";
         $listobject->querystring .= "    annualapplied, landuseid, pollutanttype, ";
         $listobject->querystring .= "    deficit, pollcapacity, defmax, pollmax) select b.subshedid, ";
         $listobject->querystring .= "    b.sublu, b.luname, b.luarea, 0, ";
         $listobject->querystring .= "    c.planduseid as landuseid, 2, ";
         $listobject->querystring .= "   b.optp, ";
         $listobject->querystring .= "    b.luarea*b.optp as pollcapacity, ";
         $listobject->querystring .= "   b.maxp, ";
         $listobject->querystring .= "    b.luarea*b.maxp as pollmax ";
         $listobject->querystring .= " from $captable as b, ";
         $listobject->querystring .= "    $lutable as c ";
         $listobject->querystring .= " where b.sublu not in ";
         $listobject->querystring .= " (select sublu from $remcap where pollutanttype = 2)";
         $listobject->querystring .= "    and b.luname = c.hspflu";
#         print("$listobject->querystring ; <br>");
         $listobject->performQuery();

      } else {
         # total table exists, therefore create from already applied
         $listobject->querystring = "create temp table $remcap as select b.subshedid, ";
         $listobject->querystring .= "    b.sublu, b.luname, b.luarea, 0 as annualapplied, ";
         $listobject->querystring .= "    c.planduseid as landuseid, 2 as pollutanttype, ";
         $listobject->querystring .= "   b.optp as deficit, ";
         $listobject->querystring .= "    b.luarea*b.optp as pollcapacity, ";
         $listobject->querystring .= "   b.maxp as defmax, ";
         $listobject->querystring .= "    b.luarea*b.maxp as pollmax ";
         $listobject->querystring .= " from $captable as b, ";
         $listobject->querystring .= "    $lutable as c ";
         $listobject->querystring .= " where b.sublu not in ";
         $listobject->querystring .= " (select sublu from $remcap where pollutanttype = 2)";
         $listobject->querystring .= "    and b.luname = c.hspflu";
#         print("$listobject->querystring ; <br>");
         $listobject->performQuery();
      }


      $listobject->querystring = "insert into $remcap (subshedid, sublu, luname, luarea, ";
      $listobject->querystring .= "    annualapplied, landuseid, pollutanttype, ";
      $listobject->querystring .= "    deficit, pollcapacity, defmax, pollmax) select b.subshedid, ";
      $listobject->querystring .= "    b.sublu, b.luname, b.luarea, 0, ";
      $listobject->querystring .= "    c.planduseid as landuseid, 1, ";
      $listobject->querystring .= "   b.optn, ";
      $listobject->querystring .= "    b.luarea*b.optn as pollcapacity, ";
      $listobject->querystring .= "   b.maxn, ";
      $listobject->querystring .= "    b.luarea*b.maxn as pollmax ";
      $listobject->querystring .= " from $captable as b, ";
      $listobject->querystring .= "    $lutable as c ";
      $listobject->querystring .= " where b.sublu not in ";
      $listobject->querystring .= " (select sublu from $remcap where pollutanttype = 1)";
      $listobject->querystring .= "    and b.luname = c.hspflu";
#         print("$listobject->querystring ; <br>");
      $listobject->performQuery();

      return $remcap;

   }

function transportManure($listobject, $scenarioid, $thisyear, $subsheds, $thisdate, $sourcetable, $debug) {

   # performs manure transport from records entered in the the table
   # scen_source_transport
   # crucial input is the $manurestoretable - the table that contains the source data

   if ($listobject->tableExists("tmp_transport") ) {
      $listobject->querystring = "drop table tmp_transport ";
      $listobject->performQuery();
   }

   if (strlen($subsheds) > 0 ) {
      $subcond = " subshedid in ($subsheds) ";
      $asubcond = " a.subshedid in ($subsheds) ";
      $bsubcond = " b.subshedid in ($subsheds) ";
   } else {
      $subcond = " ( 1 = 1 ) ";
      $asubcond = " ( 1 = 1 ) ";
      $bsubcond = " ( 1 = 1 ) ";
   }

   # calculate % of total source that should be transported
   # match on constit column for ratio ccalculation, but do not store the constit
   # since we will transport all associated constits at the same ratio
   $listobject->querystring = "  select a.sourceid, a.subshedid, b.landuseid, a.dest_subshedid, ";
   $listobject->querystring .= "    CASE ";
   $listobject->querystring .= "       WHEN a.amount > b.annualapplied THEN 1.0 ";
   $listobject->querystring .= "       ELSE a.amount/b.annualapplied ";
   $listobject->querystring .= "    END as trans_frac ";
   $listobject->querystring .= " INTO temp table tmp_transport ";
   $listobject->querystring .= " from scen_source_transport as a, $sourcetable as b ";
   $listobject->querystring .= " where a.subshedid = b.subshedid ";
   $listobject->querystring .= "    and a.sourceid = b.sourceid ";
   $listobject->querystring .= "    and a.constit = b.pollutanttype ";
   $listobject->querystring .= "    and a.storage_bin = b.landuseid ";
   $listobject->querystring .= "    and a.scenarioid = $scenarioid ";
   $listobject->querystring .= "    and a.thisyear = $thisyear ";
   $listobject->querystring .= "    and $asubcond ";
   $listobject->querystring .= "    and $bsubcond ";
   if ($debug) { print(" $listobject->querystring ; <br>"); }
   $listobject->performQuery();
   if ($debug) {
      $listobject->querystring = "  select * from tmp_transport ";
      print(" $listobject->querystring ; <br>");
      $listobject->performQuery();
      $listobject->showList();
   }



   # calculate % of total source that should be transported
   $listobject->querystring = "   insert into $sourcetable (subshedid, landuseid, sourceid, sourceclass, ";
   $listobject->querystring .= "    spreadid, sourcetypeid, pollutanttype, typeid, vconst, ";
   $listobject->querystring .= "    volatilization, storagedieoff, annualproduction, annualstored, ";
   $listobject->querystring .= "    jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec, ";
   $listobject->querystring .= "    annualdieoff, annualvolatilized, annualapplied ) ";
   $listobject->querystring .= " select b.dest_subshedid, a.landuseid, a.sourceid, a.sourceclass, ";
   $listobject->querystring .= "    a.spreadid, a.sourcetypeid, a.pollutanttype, a.typeid, a.vconst, ";
   $listobject->querystring .= "    a.volatilization, a.storagedieoff, ";
   $listobject->querystring .= "    b.trans_frac * a.annualproduction, b.trans_frac * a.annualstored, ";
   $listobject->querystring .= "    b.trans_frac * a.jan, b.trans_frac * a.feb, b.trans_frac * a.mar, ";
   $listobject->querystring .= "    b.trans_frac * a.apr, b.trans_frac * a.may, b.trans_frac * a.jun, ";
   $listobject->querystring .= "    b.trans_frac * a.jul, b.trans_frac * a.aug, b.trans_frac * a.sep, ";
   $listobject->querystring .= "    b.trans_frac * a.oct, b.trans_frac * a.nov, b.trans_frac * a.dec, ";
   $listobject->querystring .= "    b.trans_frac * a.annualdieoff, b.trans_frac * a.annualvolatilized, ";
   $listobject->querystring .= "    b.trans_frac * a.annualapplied ";
   $listobject->querystring .= " from tmp_transport as b, $sourcetable as a ";
   $listobject->querystring .= " where a.subshedid = b.subshedid ";
   $listobject->querystring .= "    and a.sourceid = b.sourceid ";
   $listobject->querystring .= "    and b.landuseid = a.landuseid ";
   $listobject->querystring .= "    and $asubcond ";
   if ($debug) { print(" $listobject->querystring ; <br>"); }
   $listobject->performQuery();

   $listobject->querystring = "  update $sourcetable set ";
   $listobject->querystring .= "    annualproduction = (1.0 - b.trans_frac) * a.annualproduction, ";
   $listobject->querystring .= "    annualstored = (1.0 - b.trans_frac) * a.annualstored, ";
   $listobject->querystring .= "    jan = (1.0 - b.trans_frac) * a.jan, feb = (1.0 - b.trans_frac) * a.feb, ";
   $listobject->querystring .= "    mar = (1.0 - b.trans_frac) * a.mar, apr = (1.0 - b.trans_frac) * a.apr, ";
   $listobject->querystring .= "    may = (1.0 - b.trans_frac) * a.may, jun = (1.0 - b.trans_frac) * a.jun, ";
   $listobject->querystring .= "    jul = (1.0 - b.trans_frac) * a.jul, aug = (1.0 - b.trans_frac) * a.aug, ";
   $listobject->querystring .= "    sep = (1.0 - b.trans_frac) * a.sep, oct = (1.0 - b.trans_frac) * a.oct, ";
   $listobject->querystring .= "    nov= (1.0 - b.trans_frac) * a.nov, dec = (1.0 - b.trans_frac) * a.dec, ";
   $listobject->querystring .= "    annualdieoff = (1.0 - b.trans_frac) * a.annualdieoff, ";
   $listobject->querystring .= "    annualvolatilized = (1.0 - b.trans_frac) * a.annualvolatilized, ";
   $listobject->querystring .= "    annualapplied = (1.0 - b.trans_frac) * a.annualapplied ";
   $listobject->querystring .= " from tmp_transport as b, $sourcetable as a ";
   $listobject->querystring .= " where a.subshedid = b.subshedid ";
   $listobject->querystring .= "    and a.sourceid = b.sourceid ";
   $listobject->querystring .= "    and a.landuseid = b.landuseid ";
   $listobject->querystring .= "    and $sourcetable.subshedid = a.subshedid ";
   $listobject->querystring .= "    and $sourcetable.sourceid = a.sourceid ";
   $listobject->querystring .= "    and $sourcetable.landuseid = a.landuseid ";
   $listobject->querystring .= "    and $sourcetable.pollutanttype = a.pollutanttype ";
   if ($debug) { print(" $listobject->querystring ; <br>"); }
   $listobject->performQuery();

}


   function createGenericCropNeed($listobject, $projectid, $pollutantid, $appfactor, $insublu, $lutable, $basename, $spreadid, $limitrate, $alreadyapplied, $storetable, $overwrite, $debug) {

      #print("Spread id = $spreadid<br>");
      # $limitrate = 0 - apply whatever is available, no concern for over-application
      # $limitrate = 1 - nutrient management principles, no over application
      # $limitrate = 2 - "unlimited supply", apply to capacity regardless of the quantity of source.
      #                  now considers the "pct_need" passed in the distro table to simulate
      #                  starter fertilizer or scoping scenario where we might say
      #                  50% should be from manure and 50% from fertilizer
      # $limitrate = 3 - apply using the custom $appfactor variable. This is to apply a static
      #                  percent of crop uptake, as would be the case for starter fertilizer
      #                  or in the case of a scoping or sensitiviy scenario where you wanted
      #                  to put a specific percent of nutrients from manure or fertilizer
      #                  ( not yet implemented )

      # $subluwactable - table with subwatershed, landuse combos

      # $lutable = landuse table for mapping sublu landuse ids

      # $pollutantid - the id of the limiting pollutant. However, if more than one pollutant

      # is associated with a given source, all associated pollutatants will be applied
      # however, the limiting one will be that which governs the distribution
      # amnongst the landuses and with regard to a nutrient management limit if applicable.

      # $alreadyapplied - this table contains all the loads that have already been applied
      # this will be used to determine an available capacity table, rather than
      # using the total capacity table as calculated, if supplied. If this is not desired
      # $alreadyapplied should be set to ''

      # $storetable - contains the loads to be distributed. This table is updated so that any
      # load that is distrbuted during this operation is subtracted, leaving the remainder
      # in the $storetable

      $subluwactable = $basename . "_sublu";
      $totalwactable = $basename . "_total";
      $ratiotable = $basename . "_ratio";
      $portiontable = $basename . "_portion";
      $appliedtable = $basename . "_applied";
      $sumappliedtable = $basename . "_sumapplied";
      $monapptable = $basename . "_monapp";
      $facttbl = $basename . "_fact";
      $scaletbl = $basename . "_scale";
      $subshedstore = $basename . "_shedstore";

      if ($listobject->tableExists($subluwactable) ) {
         if (! $overwrite) {
          print("<b>Warning:</b>Table $subluwactable already exists. Will not overwrite<br>");
          return;
         } else {
          $listobject->querystring = "drop table $subluwactable";
          $listobject->performQuery();
          $listobject->querystring = "drop table $totalwactable";
          $listobject->performQuery();
          $listobject->querystring = "drop table $ratiotable";
          $listobject->performQuery();
          $listobject->querystring = "drop table $portiontable";
          $listobject->performQuery();
          $listobject->querystring = "drop table $appliedtable";
          $listobject->performQuery();
          $listobject->querystring = "drop table $monapptable";
          $listobject->performQuery();
          $listobject->querystring = "drop table $facttbl";
          $listobject->performQuery();
          $listobject->querystring = "drop table $scaletbl";
          $listobject->performQuery();
          $listobject->querystring = "drop table $subshedstore";
          $listobject->performQuery();
         }
      }

      # create the generic stored load tables by sublu and subshed for this spreadid
      if ($storetable == '') {
         # send 1 as $calcloss parameter, since we don't know
         $storetable = makeGenericStored($listobject, $projectid, $basename, $spreadid, 1, $overwrite, $debug);
      }

      # sum up 'annualapplied' column because this represents total available for
      # application after all losses are considered.
      $listobject->querystring = "create temp table $subshedstore as select subshedid, ";
      $listobject->querystring .= "sum(annualapplied) as totalstored, pollutanttype ";
      $listobject->querystring .= "    from $storetable";
      $listobject->querystring .= "    group by subshedid, pollutanttype";
      $listobject->performQuery();

      # this selects which column in the sublu table to use for assimilative capacity
      # this should be changed later, so that the capacities are not stored in the sublu
      # table, but in a mapping table, in order to allow for unlimited pollutants
      # then, the capacity table will be reference in a sub-query on projectid, sublu,
      # and pollutanttype
      # for now, the limiting constit must be some species of N or P
      $listobject->querystring = " select master_constit from pollutanttype where typeid = $pollutantid";
      $listobject->performQuery();
      $switchid = $listobject->getRecordValue(1,'master_constit');
      switch($switchid) {
         case 1:
            $optcol = 'optn';
            $maxcol = 'maxn';
         break;

         case 2:
            $optcol = 'optp';
            $maxcol = 'maxp';
         break;

      }

      # create Waste Assimilative Capacity table

      if ($alreadyapplied <> '') {

         # call routine to create a remaining capacity table for nutrient management purposes
         # $alreadyapplied is the table with total loads so far applied
         # $insublu = the input working sublu table
         # $lutable - table of landuses
         # creates entries for both total N and total P
         $subluwactable = createRemainingCapacity2( $listobject, $projectid, $basename, $alreadyapplied, $insublu, $lutable, $overwrite, $debug);
         #print("$subluwactable <br>");

      } else {

         # Otherwise, it will assume that nothing has been distributed onto this group
         # so far
         $listobject->querystring = "  create temp table $subluwactable as select a.subshedid, ";
         $listobject->querystring .= " a.sublu, a.luname, a.luarea, a.$optcol, $maxcol, ";
         $listobject->querystring .= " b.planduseid as landuseid, $pollutantid as pollutanttype, ";
         $listobject->querystring .= " a.luarea * a.$optcol as pollcapacity, ";
         $listobject->querystring .= " a.luarea * a.$maxcol as pollmax ";
         $listobject->querystring .= "    from $insublu as a, ";
         $listobject->querystring .= "       $lutable as b, workdistro as c ";
         $listobject->querystring .= "    where a.luname = b.hspflu";
         $listobject->querystring .= "       and a.luarea > 0 ";
         $listobject->querystring .= "       and b.landuseid = c.landuseid ";
         $listobject->querystring .= "       and c.spreadid = $spreadid ";
         $listobject->querystring .= "       and a.subshedid = c.subshedid ";
         $listobject->performQuery();
      }

      # debug

/*
         $listobject->querystring = "select * from $subluwactable ";
         $listobject->performQuery();
         $listobject->showList();
         die;
*/

      # total up all acre capacities for calculating ratios
      $listobject->querystring = "create temp table $totalwactable as select a.subshedid, ";
      $listobject->querystring .= " a.pollutanttype, sum(a.pollcapacity) as pollcapacity, ";
      $listobject->querystring .= " sum(a.pollmax) as maxcapacity ";
      $listobject->querystring .= "    from $subluwactable as a, $lutable as b, workdistro as c ";
      $listobject->querystring .= "    where a.pollcapacity >= 0 ";
      $listobject->querystring .= "       and a.luname = b.hspflu ";
      $listobject->querystring .= "       and b.landuseid = c.landuseid ";
      $listobject->querystring .= "       and c.spreadid = $spreadid ";
      $listobject->querystring .= "       and a.subshedid = c.subshedid ";
      $listobject->querystring .= "    group by a.subshedid, a.pollutanttype";
      $listobject->performQuery();

      if ($debug) {
         $listobject->querystring = "select * from $totalwactable";
         $listobject->performQuery();
         $listobject->showList();
         #die;
      }


      # now we create the table of distribution ratios for each land use in a sub-watershed
      # this resulting ratio, tcnsr, determines what percent of the available constituent
      # goes to each land use in a subwatershed, based on optimal need. The sum of all "tcnsr" in a
      # subshed should equal 1.0
      # similarly, "tmaxr" is the ratio of max capacity in a landuse to the total in the subshed
      switch ($limitrate) {

         case 2:

            # this option simply fills each landuse in each sub-shed to capacity
            # it is really independent of the amount of constituent available
            # this is used primarily for fertilizer, when the total rate is known,
            # and we just want to supplement the other organic forms of nutrient that
            # have already gone down.

            $listobject->querystring = "  create temp table $ratiotable as select a.subshedid,";
            $listobject->querystring .= " a.sublu, a.pollutanttype, a.landuseid, a.luname, ";
            # totalwac is an un-used variable, so we set it to a dummy
            $listobject->querystring .= " a.pollcapacity as thiswac, a.pollcapacity as totalwac, ";
            # set this ratio to the ratio of need to available
            # even if more is needed than available, this won't mind, since this is a filler up
            # kind of deall, and a ratio > 1.0 will simple "create" more constituent
            $listobject->querystring .= " (a.pollcapacity / b.totalstored) as tcnsr, ";
            # we grab thge pct_need column also, this will be used to limit the percent of
            # the total need that will be fulfilled by this particular distribution
            # for example, if starter fertilizer should be 20% of need, then this would be
            # set to 0.2 in the distro definition
            $listobject->querystring .= " 1 as tmaxr, c.pct_need ";
            $listobject->querystring .= "    from $subluwactable as a, ";
            $listobject->querystring .= "       $subshedstore as b, workdistro as c, $lutable as d ";
            $listobject->querystring .= "    where a.subshedid = b.subshedid ";
            $listobject->querystring .= "       and a.pollcapacity > 0";
            $listobject->querystring .= "       and a.luname = d.hspflu ";
            $listobject->querystring .= "       and d.landuseid = c.landuseid ";
            $listobject->querystring .= "       and c.spreadid = $spreadid ";
            $listobject->querystring .= "       and c.subshedid = a.subshedid ";
            $listobject->querystring .= "       and a.pollutanttype = $pollutantid ";
            $listobject->querystring .= "       and b.pollutanttype = $pollutantid ";
            $listobject->performQuery();

         break;


         default:
         # this default behaviour assumes that there is a finite amount of constituent available,
         # so the various land uses each get a portion of that based on their available assimilation
         # capacity (need)
         # this is the same for either nutrient-management distro, where we limit the total to a
         # certain application rate, and non-nutrient limited, which means that all the constituent
         # that is available gets applied to all land uses based on their assimilative capacity,
         # even if the total distribution exceeds the assimilative capacity

            $listobject->querystring = "create temp table $ratiotable as select a.subshedid,";
            $listobject->querystring .= " a.sublu, a.pollutanttype, a.landuseid, a.luname, ";
            $listobject->querystring .= " a.pollcapacity as thiswac, b.pollcapacity as totalwac, ";
            $listobject->querystring .= " (a.pollcapacity / b.pollcapacity) as tcnsr, ";
            $listobject->querystring .= " (a.pollmax / b.maxcapacity) as tmaxr, c.pct_need ";
            $listobject->querystring .= "    from $subluwactable as a, ";
            $listobject->querystring .= "       $totalwactable as b, workdistro as c, $lutable as d";
            $listobject->querystring .= "    where a.subshedid = b.subshedid ";
            $listobject->querystring .= "       and a.pollcapacity > 0";
            $listobject->querystring .= "       and a.luname = d.hspflu ";
            $listobject->querystring .= "       and d.landuseid = c.landuseid ";
            $listobject->querystring .= "       and c.spreadid = $spreadid ";
            $listobject->querystring .= "       and c.subshedid = a.subshedid ";
            $listobject->querystring .= "       and a.pollutanttype = b.pollutanttype ";
            $listobject->querystring .= "       and a.pollutanttype = $pollutantid ";
            $listobject->performQuery();
         break;
         }
         if ($debug) {
            print("$listobject->querystring ; <br>");
            $listobject->querystring = "select * from $ratiotable order by landuseid, subshedid";
            $listobject->performQuery();
            $listobject->showList();
         }

      # this factor table pertains to the relationship between available consituent and
      # assimilative capacity.
      # scaling factor table for limiting nutrient application, as in the case of nutrient
      # management. If no nutrient management is used, this scale factor (tnmr) value is set to
      # 1.0, i.e., no reduction.
      # if more is available than allowed, this rate goes down to less than 1.0
      # $facttbl = tnmrtable = $basename . "_fact"
      # $scaletbl = tnmrscaletbl = $basename . "_scale"
      # need inputs of "wac" table and "stored" table

      # tnmr - used to limit the application to a certain threshold below the need value (1.0 or less)
      # tcnsr - the crop need ratio, leterally, the applied vs. removal reccomended multiplier,
      #         i.e., 1.25 for typical application reccomendation on crop land

      switch ($limitrate) {

         case 0:

            # no rate limits, over-application allowed, all stored will be applied
            $listobject->querystring = "create temp table $facttbl as select a.subshedid, ";
            $listobject->querystring .= "a.pollutanttype, 1 as tnmr ";
            $listobject->querystring .= "    from $totalwactable as a, ";
            $listobject->querystring .= "       $subshedstore as b";
            $listobject->querystring .= "    where a.subshedid = b.subshedid ";
            $listobject->querystring .= "       and a.pollutanttype = b.pollutanttype ";
            $listobject->querystring .= "       and a.pollutanttype = $pollutantid ";
            $listobject->querystring .= "       and b.totalstored > 0 ";

       #     print("$listobject->querystring ; <br>");
            $listobject->performQuery();
         break;

         case 2:

            # since this distro applies exactly what is needed regardless of supply,
            # we set this to one. We still need to have some stored for this to work.
            # even a dummy amount of 1.0
            $listobject->querystring = "create temp table $facttbl as select a.subshedid, ";
            $listobject->querystring .= "a.pollutanttype, 1 as tnmr ";
            $listobject->querystring .= "    from $totalwactable as a, ";
            $listobject->querystring .= "       $subshedstore as b";
            $listobject->querystring .= "    where a.subshedid = b.subshedid ";
            $listobject->querystring .= "       and a.pollutanttype = $pollutantid ";
            $listobject->querystring .= "       and b.pollutanttype = $pollutantid ";
            $listobject->querystring .= "       and b.totalstored > 0 ";

          #  print("$listobject->querystring ; <br>");
            $listobject->performQuery();
         break;


         case 1:

            $listobject->querystring = "create temp table $facttbl as select a.subshedid, ";
            # commented out to try new distro scheme with pollutant limiting
            # added for limiting maximum application above optimum on non-NM lus
            $listobject->querystring .= "a.pollutanttype, (a.pollcapacity / b.totalstored) as tnmr, ";
            $listobject->querystring .= " (a.maxcapacity/b.totalstored) as mtnmr, ";
            $listobject->querystring .= " b.totalstored ";
            $listobject->querystring .= "    from $totalwactable as a, ";
            $listobject->querystring .= "       $subshedstore as b";
            $listobject->querystring .= "    where a.subshedid = b.subshedid ";
            $listobject->querystring .= "       and a.pollutanttype = b.pollutanttype ";
            $listobject->querystring .= "       and b.totalstored > 0 ";
            $listobject->performQuery();

        #    print("$listobject->querystring ; <br>");

            # if assimilative capacity  exceeds available constituent, we set the rations = 1.0
            # since we cannot apply more than exists
            $listobject->querystring = "update $facttbl set tnmr = 1.0 ";
            $listobject->querystring .= "where tnmr > 1.0";
            $listobject->performQuery();
      #      print("$listobject->querystring ; <br>");

            $listobject->querystring = "update $facttbl set mtnmr = 1.0 ";
            $listobject->querystring .= "where mtnmr > 1.0";
            $listobject->performQuery();
       #     print("$listobject->querystring ; <br>");

            # if the tnmr is less than 1.0, it means that more constituent is available
            # than capacity in the watershed to assimilate it.
            # therefore we switch to the max rate share (tmaxr) method of partitioning
            # what is available.
            # we only do this however, if tnmr < 0.95, since there might be a slight
            # over application, and that is OK since rounding errors can cause some issues.
            # Under standard nutrient management, both tmax and tcnsr may be equal,
            # so nothing changes. However, in the case of nitrogen, the maxn parameter
            # may be calculated such that legume fixation is suppressed (based on max uptake
            # instead of optimal crop need), and therefore some more nutrients may be shifted to this
            # land use, although the max will never exceed the appropriate rate.
            # Under a schema whereby we are seeking to limit the
            # nutrients to a max that will not adversely effect plant growth, these
            # will differ. If the nutrient in question does not exceed the total WAC
            # in the subshed, we use the original ratios
            $listobject->querystring = "update $ratiotable set tcnsr = tmaxr ";
            $listobject->querystring .= "    where subshedid in ( ";
            $listobject->querystring .= "       select subshedid from $facttbl ";
            $listobject->querystring .= "          where tnmr < 0.95 ) ";
            $listobject->performQuery();
        #    print("$listobject->querystring ; <br>");

            # tnmr < 1.0, so we switch to the max method, once again, if we have
            # the optimal and max rates the same (as we should under nutrient management)
            # this does not affect the outcome
            $listobject->querystring = "update $facttbl set tnmr = mtnmr ";
            $listobject->querystring .= "where tnmr < 0.95";
            $listobject->performQuery();
       #     print("$listobject->querystring ; <br>");

            $listobject->querystring = "update $facttbl set tnmr = 0.0 ";
            $listobject->querystring .= "where tnmr < 0.0";
            $listobject->performQuery();
        #    print("$listobject->querystring ; <br>");

            # scale table
            $listobject->querystring = "create temp table $scaletbl as select subshedid, ";
            $listobject->querystring .= "(1.0 / sum(tnmr)) as tnmrscale, (1.0 - sum(tnmr)) as tnmrred ";
            $listobject->querystring .= "    from $facttbl ";
            $listobject->querystring .= "    where tnmr > 0 ";
            # added for limiting maximum application above optimum on non-NM lus
            # new, does this stop the craziness??
            $listobject->querystring .= "       and pollutanttype = $pollutantid ";
            $listobject->querystring .= "    group by subshedid ";
            $listobject->performQuery();
        #    print("$listobject->querystring ; <br>");

            $listobject->querystring = "update $scaletbl set tnmrred = 0.0 ";
            $listobject->querystring .= "where tnmrred < 0.0";
            $listobject->performQuery();
            #print("$listobject->querystring ; <br>");

            $listobject->querystring = "update $facttbl set tnmr = ";
            $listobject->querystring .= "   ($scaletbl.tnmrscale * $facttbl.tnmr) ";
            $listobject->querystring .= "where $facttbl.subshedid = $scaletbl.subshedid ";
            $listobject->querystring .= "   and $scaletbl.tnmrscale < 1.0 ";
            $listobject->performQuery();
            #print("$listobject->querystring ; <br>");
         break;

      }


      # creates a table of all daily load production that goes to a destination landuse
      # from storage for acres under a crop need plan

      switch ($limitrate) {

         default:
            $listobject->querystring = "create temp table $portiontable as select b.subshedid, ";
            $listobject->querystring .= " c.sublu, b.sourceid, b.sourceclass,  ";
            $listobject->querystring .= " b.pollutanttype, b.annualstored, ";
            $listobject->querystring .= " a.tnmr, c.tcnsr, b.annualapplied, ";
            $listobject->querystring .= " b.annualdieoff, b.typeid, c.landuseid, $spreadid as spreadid, ";
            $listobject->querystring .= " b.annualvolatilized, b.sourcetypeid, ";
            # old - did not consider the restriction on percent of need that could be satisfied
            #       by this particular distro, for example, start fertilizer
            # $listobject->querystring .= " (c.pct_need * a.tnmr * c.tcnsr * b.annualapplied) as cnapplied, ";
            # new - considers that this distro may be limited to only satisfy a certain percentage
            #       of the total crop need.
            $listobject->querystring .= " (c.pct_need * a.tnmr * c.tcnsr * b.annualapplied) as cnapplied, ";
            $listobject->querystring .= " c.luname ";
            $listobject->querystring .= "from $storetable as b, ";
            $listobject->querystring .= "    $facttbl as a, ";
            $listobject->querystring .= "    $ratiotable as c ";
            $listobject->querystring .= "    where b.subshedid = c.subshedid ";
            #$listobject->querystring .= "    and a.pollutanttype = b.pollutanttype ";
            $listobject->querystring .= "    and a.pollutanttype = c.pollutanttype ";
            $listobject->querystring .= "    and a.subshedid = c.subshedid ";
            $listobject->querystring .= "    and b.sourceid in (select sourceid from $storetable ";
            $listobject->querystring .= "       where pollutanttype = $pollutantid ";
            $listobject->querystring .= "       group by sourceid  ) ";
            $listobject->tablename = '';
            $listobject->performQuery();

         break;
      }

      if ($debug) {
         $listobject->querystring = "  select b.subshedid, b.luname, a.sourcename, b.sourceid, ";
         $listobject->querystring .= "   b.pollutanttype, b.annualapplied, b.tnmr, b.tcnsr, b.cnapplied ";
         $listobject->querystring .= " FROM $portiontable as b, sources as a ";
         $listobject->querystring .= " WHERE a.sourceid = b.sourceid ";
         $listobject->performQuery();
         $listobject->showList();
      }


      #print("$listobject->querystring ; <br>");

      $listobject->querystring = "create temp table $appliedtable as select a.subshedid, ";
      $listobject->querystring .= "a.sublu, b.landuseid, a.luname, a.sourceid, a.sourceclass, ";
      $listobject->querystring .= "a.sourcetypeid, a.pollutanttype, a.typeid, $spreadid as spreadid, ";
      $listobject->querystring .= " a.cnapplied as annualapplied, ";
      $listobject->querystring .= "(b.JAN * a.cnapplied) / c.JAN as JAN, ";
      $listobject->querystring .= "(b.FEB * a.cnapplied) / c.FEB as FEB, ";
      $listobject->querystring .= "(b.MAR * a.cnapplied) / c.MAR as MAR, ";
      $listobject->querystring .= "(b.APR * a.cnapplied) / c.APR as APR, ";
      $listobject->querystring .= "(b.MAY * a.cnapplied) / c.MAY as MAY, ";
      $listobject->querystring .= "(b.JUN * a.cnapplied) / c.JUN as JUN, ";
      $listobject->querystring .= "(b.JUL * a.cnapplied) / c.JUL as JUL, ";
      $listobject->querystring .= "(b.AUG * a.cnapplied) / c.AUG as AUG, ";
      $listobject->querystring .= "(b.SEP * a.cnapplied) / c.SEP as SEP, ";
      $listobject->querystring .= "(b.OCT * a.cnapplied) / c.OCT as OCT, ";
      $listobject->querystring .= "(b.NOV * a.cnapplied) / c.NOV as NOV, ";
      $listobject->querystring .= "(b.DEC * a.cnapplied) / c.DEC as DEC";
      $listobject->querystring .= "    from $portiontable as a,";
      $listobject->querystring .= "         workdistro as b, ";
      $listobject->querystring .= "         monthdays as c";
      $listobject->querystring .= "    where b.spreadid = $spreadid";
      $listobject->querystring .= "    and c.spreadid = 4";
      $listobject->querystring .= "    and b.landuseid = a.landuseid";
      $listobject->querystring .= "    and b.subshedid = a.subshedid";
      $listobject->performQuery();
      #print("$listobject->querystring<br><br>");


      $listobject->querystring = "update $appliedtable set landuseid = a.luid ";
      $listobject->querystring .= "    from $lutable as a ";
      $listobject->querystring .= "    where $appliedtable.luname = a.hspflu ";
#      $listobject->querystring .= "    where $appliedtable.landuseid = a.planduseid ";
#      $listobject->querystring .= "       and a.planduseid = a.landuseid ";
      $listobject->performQuery();


      $listobject->querystring = "create temp table $monapptable as select ";
      $listobject->querystring .= "a.subshedid, a.sublu, a.landuseid, a.pollutanttype, ";
      $listobject->querystring .= "0.0 as annualapplied ,";
      $listobject->querystring .= "a.JAN*b.JAN as JAN,";
      $listobject->querystring .= "a.FEB*b.FEB as FEB,";
      $listobject->querystring .= "a.MAR*b.MAR as MAR,";
      $listobject->querystring .= "a.APR*b.APR as APR,";
      $listobject->querystring .= "a.MAY*b.MAY as MAY,";
      $listobject->querystring .= "a.JUN*b.JUN as JUN,";
      $listobject->querystring .= "a.JUL*b.JUL as JUL,";
      $listobject->querystring .= "a.AUG*b.AUG as AUG,";
      $listobject->querystring .= "a.SEP*b.SEP as SEP,";
      $listobject->querystring .= "a.OCT*b.OCT as OCT,";
      $listobject->querystring .= "a.NOV*b.NOV as NOV,";
      $listobject->querystring .= "a.DEC*b.DEC as DEC";
      $listobject->querystring .= "    from $appliedtable as a, ";
      $listobject->querystring .= "         monthdays as b ";
      $listobject->querystring .= "    where b.spreadid = 4";
      $listobject->performQuery();


      $listobject->querystring = "update $monapptable set annualapplied = ";
      $listobject->querystring .= "( JAN +";
      $listobject->querystring .= "FEB + ";
      $listobject->querystring .= "MAR + ";
      $listobject->querystring .= "APR + ";
      $listobject->querystring .= "MAY + ";
      $listobject->querystring .= "JUN + ";
      $listobject->querystring .= "JUL + ";
      $listobject->querystring .= "AUG + ";
      $listobject->querystring .= "SEP + ";
      $listobject->querystring .= "OCT + ";
      $listobject->querystring .= "NOV + ";
      $listobject->querystring .= "DEC )";
      $listobject->performQuery();


      # create a table of summarized applications to calculate the mass
      # balance for each source
      $listobject->querystring = "create temp table $sumappliedtable as ";
      $listobject->querystring .= "  select sourceid, pollutanttype, subshedid, ";
      $listobject->querystring .= " sum(annualapplied) as totalapplied ";
      $listobject->querystring .= "from $appliedtable as b ";
      $listobject->querystring .= "    group by subshedid, sourceid, pollutanttype ";
      $listobject->performQuery();

      # subtract the stuff that is applied from the storage table
      # unless this is a limitrate = 2, in which case this is irrelevant
      if (!($limitrate == 2)) {
         $listobject->querystring = "update $storetable ";
         $listobject->querystring .= "   set annualapplied = $storetable.annualapplied ";
         $listobject->querystring .= " - b.totalapplied ";
         $listobject->querystring .= "from $sumappliedtable as b ";
         $listobject->querystring .= "    where $storetable.subshedid = b.subshedid ";
         $listobject->querystring .= "    and $storetable.pollutanttype = b.pollutanttype ";
         $listobject->querystring .= "    and $storetable.sourceid = b.sourceid ";
         $listobject->performQuery();

         #print("$listobject->querystring ; <br>");
      }

    }


    function makeNMRatioTables($listobject, $projectid, $overwrite, $debug) {

       # creates a table of all daily load production that goes to a destination landuse
       # this includes everything but the storge landuse which goes into a separate
       # routine.
       if ($listobject->tableExists('tnmrtable') and !$overwrite) {
          print("<b>Warning:</b>Table tnmrtable already exists. Will not overwrite<br>");
          return;
       }
       if ( !($listobject->tableExists('totalnmwactable')) ) {
          makeWACTable($listobject, $projectid, $overwrite, $debug);
       }
       if ( !($listobject->tableExists('subshedstored')) ) {
          makeSubShedStored($listobject, $projectid, $overwrite, $debug);
       }

       $prevdebug = $listobject->debug;
       $listobject->debug = $debug;

       $listobject->querystring = "create temp table tnmrtable as select a.subshedid, ";
       $listobject->querystring .= "a.pollutanttype, (a.pollcapacity / b.totalstored) as tnmr ";
       $listobject->querystring .= "    from totalnmwactable as a, ";
       $listobject->querystring .= "       subshedstored as b";
       $listobject->querystring .= "    where a.subshedid = b.subshedid ";
       $listobject->querystring .= "       and a.pollutanttype = b.pollutanttype ";
       $listobject->querystring .= "       and b.totalstored > 0 ";
       $listobject->performQuery();

       #print("$listobject->querystring ; <br>");

       $listobject->querystring = "update tnmrtable set tnmr = 1.0 ";
       $listobject->querystring .= "where tnmr > 1.0";
       $listobject->performQuery();
       #print("$listobject->querystring ; <br>");

       $listobject->querystring = "create temp table tnmrscaletbl as select subshedid, ";
       $listobject->querystring .= "(1.0 / sum(tnmr)) as tnmrscale, (1.0 - sum(tnmr)) as tnmrred ";
       $listobject->querystring .= "    from tnmrtable ";
       $listobject->querystring .= "    where tnmr > 0 ";
       $listobject->querystring .= "    group by subshedid ";
       $listobject->performQuery();
       #print("$listobject->querystring ; <br>");

       $listobject->querystring = "update tnmrscaletbl set tnmrred = 0.0 ";
       $listobject->querystring .= "where tnmrred < 0.0";
       $listobject->performQuery();
       #print("$listobject->querystring ; <br>");

       $listobject->querystring = "update tnmrtable set tnmr = ";
       $listobject->querystring .= "   (tnmrscaletbl.tnmrscale * tnmrtable.tnmr) ";
       $listobject->querystring .= "where tnmrtable.subshedid = tnmrscaletbl.subshedid ";
       $listobject->querystring .= "   and tnmrscaletbl.tnmrscale < 1.0 ";
       $listobject->performQuery();
       #print("$listobject->querystring ; <br>");

       $listobject->querystring = "create temp table tsrtable as select a.subshedid, a.sublu, ";
       $listobject->querystring .= "a.pollutanttype, a.landuseid, a.luname, ";
       $listobject->querystring .= " (a.pollcapacity / b.pollcapacity) as tsr ";
       $listobject->querystring .= "    from sublunmwactable as a, ";
       $listobject->querystring .= "       totalnmwactable as b";
       $listobject->querystring .= "    where a.subshedid = b.subshedid ";
       $listobject->querystring .= "       and a.pollutanttype = b.pollutanttype ";
       $listobject->querystring .= "       and b.pollcapacity > 0 ";
       $listobject->performQuery();
       #print("$listobject->querystring ; <br>");

       $listobject->querystring = "create temp table tcnsrtable as select a.subshedid, a.sublu, ";
       $listobject->querystring .= "a.landuseid, a.luname, ";
       $listobject->querystring .= " (a.pollcapacity / b.pollcapacity) as tcnsr ";
       $listobject->querystring .= "    from sublucnwactable as a, ";
       $listobject->querystring .= "       totalcnwactable as b";
       $listobject->querystring .= "    where a.subshedid = b.subshedid ";
       $listobject->querystring .= "       and a.landuseid in (select landuseid from workdistro where spreadid = 6)";
       $listobject->performQuery();

       $listobject->debug = $prevdebug;

   }

   function makeMonNMApplied($listobject, $projectid, $overwrite, $debug) {

      # creates a table of all daily load production that goes to a destination landuse
      # from storage for acres under a nutrient management plan
      if ($listobject->tableExists('nmsubluportions') and !$overwrite) {
         print("<b>Warning:</b>Table nmsubluportions already exists. Will not overwrite<br>");
         return;
      }
      if ( !($listobject->tableExists('tnmrtable')) ) {
         makeNMRatioTables($listobject, $projectid, $overwrite, $debug);
      }

      $prevdebug = $listobject->debug;
      $listobject->debug = $debug;

      $listobject->querystring = "create temp table nmsubluportions as select a.subshedid, ";
      $listobject->querystring .= " c.sublu, b.sourceid, b.sourceclass, b.pollutanttype, b.annualstored, ";
      $listobject->querystring .= " b.annualapplied, b.annualdieoff, b.typeid, c.landuseid, ";
      $listobject->querystring .= " b.annualvolatilized, b.sourcetypeid, ";
      $listobject->querystring .= " (a.tnmr * c.tsr * b.annualapplied) as nmapplied, c.luname ";
      $listobject->querystring .= " from tnmrtable as a, ";
      $listobject->querystring .= "    annualstored as b, ";
      $listobject->querystring .= "    tsrtable as c ";
      $listobject->querystring .= " where a.subshedid = b.subshedid ";
      #$listobject->querystring .= "    and a.pollutanttype = b.pollutanttype ";
      $listobject->querystring .= "    and a.pollutanttype = c.pollutanttype ";
      $listobject->querystring .= "    and a.subshedid = c.subshedid ";
      $listobject->tablename = '';
      $listobject->performQuery();


      $listobject->querystring = "create temp table nutmanapplied as select a.subshedid, ";
      $listobject->querystring .= "a.sublu, b.landuseid, a.luname, a.sourceid, a.sourceclass, ";
      $listobject->querystring .= "a.sourcetypeid, a.pollutanttype, a.typeid, ";
      $listobject->querystring .= " a.nmapplied as annualapplied, ";
      $listobject->querystring .= "(b.JAN * a.nmapplied) / c.JAN as JAN, ";
      $listobject->querystring .= "(b.FEB * a.nmapplied) / c.FEB as FEB, ";
      $listobject->querystring .= "(b.MAR * a.nmapplied) / c.MAR as MAR, ";
      $listobject->querystring .= "(b.APR * a.nmapplied) / c.APR as APR,";
      $listobject->querystring .= "(b.MAY * a.nmapplied) / c.MAY as MAY, ";
      $listobject->querystring .= "(b.JUN * a.nmapplied) / c.JUN as JUN, ";
      $listobject->querystring .= "(b.JUL * a.nmapplied) / c.JUL as JUL, ";
      $listobject->querystring .= "(b.AUG * a.nmapplied) / c.AUG as AUG, ";
      $listobject->querystring .= "(b.SEP * a.nmapplied) / c.SEP as SEP, ";
      $listobject->querystring .= "(b.OCT * a.nmapplied) / c.OCT as OCT, ";
      $listobject->querystring .= "(b.NOV * a.nmapplied) / c.NOV as NOV, ";
      $listobject->querystring .= "(b.DEC * a.nmapplied) / c.DEC as DEC";
      $listobject->querystring .= "    from nmsubluportions as a,";
      $listobject->querystring .= "         workdistro as b,  ";
      $listobject->querystring .= "         monthdays as c";
      $listobject->querystring .= "    where ";
      $listobject->querystring .= "        b.spreadid = 5";
      $listobject->querystring .= "    and c.spreadid = 4";
      $listobject->querystring .= "    and b.landuseid = a.landuseid";
      $listobject->performQuery();

      $listobject->querystring = "update nutmanapplied set landuseid = a.luid ";
      $listobject->querystring .= "    from worklanduses as a ";
      $listobject->querystring .= "    where nutmanapplied.landuseid = a.planduseid ";
      $listobject->querystring .= "       and nutmanapplied.landuseid <> a.landuseid ";
      $listobject->performQuery();


      $listobject->querystring = "create temp table nutmantotal as select ";
      $listobject->querystring .= "a.subshedid, a.sublu, a.landuseid, a.pollutanttype, ";
      $listobject->querystring .= "0.0 as annualapplied ,";
      $listobject->querystring .= "a.JAN*b.JAN as JAN,";
      $listobject->querystring .= "a.FEB*b.FEB as FEB,";
      $listobject->querystring .= "a.MAR*b.MAR as MAR,";
      $listobject->querystring .= "a.APR*b.APR as APR,";
      $listobject->querystring .= "a.MAY*b.MAY as MAY,";
      $listobject->querystring .= "a.JUN*b.JUN as JUN,";
      $listobject->querystring .= "a.JUL*b.JUL as JUL,";
      $listobject->querystring .= "a.AUG*b.AUG as AUG,";
      $listobject->querystring .= "a.SEP*b.SEP as SEP,";
      $listobject->querystring .= "a.OCT*b.OCT as OCT,";
      $listobject->querystring .= "a.NOV*b.NOV as NOV,";
      $listobject->querystring .= "a.DEC*b.DEC as DEC";
      $listobject->querystring .= "    from nutmanapplied as a, ";
      $listobject->querystring .= "         monthdays as b ";
      $listobject->performQuery();


      $listobject->querystring = "update nutmantotal set annualapplied = ";
      $listobject->querystring .= "( JAN +";
      $listobject->querystring .= "FEB + ";
      $listobject->querystring .= "MAR + ";
      $listobject->querystring .= "APR + ";
      $listobject->querystring .= "MAY + ";
      $listobject->querystring .= "JUN + ";
      $listobject->querystring .= "JUL + ";
      $listobject->querystring .= "AUG + ";
      $listobject->querystring .= "SEP + ";
      $listobject->querystring .= "OCT + ";
      $listobject->querystring .= "NOV + ";
      $listobject->querystring .= "DEC )";
      $listobject->performQuery();
      $listobject->debug = $prevdebug;

      # subtract manure from storage that has already gone onto nutrient management acres
      # by using tnmr table (total nutrient management ratio) as factor to decrease
      $listobject->querystring = "update annualstored set annualapplied = ";
      $listobject->querystring .= "( annualstored.annualapplied * a.tnmrred ) ";
      $listobject->querystring .= "    from tnmrscaletbl as a ";
      $listobject->querystring .= "    where annualstored.subshedid = a.subshedid ";
      $listobject->performQuery();


      $listobject->debug = $prevdebug;

   }

   function makeMonCropNeedApplied($listobject, $projectid, $overwrite, $debug) {

      # creates a table of all daily load production that goes to a destination landuse
      # from storage for acres under a nutrient management plan
      if ($listobject->tableExists('subluportions') and !$overwrite) {
         print("<b>Warning:</b>Table subluportions already exists. Will not overwrite<br>");
         return;
      }
      if ( !($listobject->tableExists('tnmrtable')) ) {
         makeNMRatioTables($listobject, $projectid, $overwrite, $debug);
      }

      $prevdebug = $listobject->debug;
      $listobject->debug = $debug;

      $listobject->querystring = "create temp table subluportions as select b.subshedid, ";
      $listobject->querystring .= " c.sublu, b.sourceid, b.sourceclass, b.pollutanttype, b.annualstored, ";
      $listobject->querystring .= " c.tcnsr, b.annualapplied, b.annualdieoff, b.typeid, c.landuseid, ";
      $listobject->querystring .= " b.annualvolatilized, b.sourcetypeid, ";
      $listobject->querystring .= " (c.tcnsr * b.annualapplied) as cnapplied, c.luname ";
      $listobject->querystring .= "from annualstored as b, ";
      $listobject->querystring .= "    tcnsrtable as c ";
      $listobject->querystring .= "    where b.subshedid = c.subshedid ";
      $listobject->tablename = '';
      $listobject->performQuery();


      $listobject->querystring = "create temp table cropneedapplied as select a.subshedid, ";
      $listobject->querystring .= "a.sublu, b.landuseid, a.luname, a.sourceid, a.sourceclass, ";
      $listobject->querystring .= "a.sourcetypeid, a.pollutanttype, a.typeid, ";
      $listobject->querystring .= " a.cnapplied as annualapplied, ";
      $listobject->querystring .= "(b.JAN * a.cnapplied) / c.JAN as JAN, ";
      $listobject->querystring .= "(b.FEB * a.cnapplied) / c.FEB as FEB, ";
      $listobject->querystring .= "(b.MAR * a.cnapplied) / c.MAR as MAR, ";
      $listobject->querystring .= "(b.APR * a.cnapplied) / c.APR as APR, ";
      $listobject->querystring .= "(b.MAY * a.cnapplied) / c.MAY as MAY, ";
      $listobject->querystring .= "(b.JUN * a.cnapplied) / c.JUN as JUN, ";
      $listobject->querystring .= "(b.JUL * a.cnapplied) / c.JUL as JUL, ";
      $listobject->querystring .= "(b.AUG * a.cnapplied) / c.AUG as AUG, ";
      $listobject->querystring .= "(b.SEP * a.cnapplied) / c.SEP as SEP, ";
      $listobject->querystring .= "(b.OCT * a.cnapplied) / c.OCT as OCT, ";
      $listobject->querystring .= "(b.NOV * a.cnapplied) / c.NOV as NOV, ";
      $listobject->querystring .= "(b.DEC * a.cnapplied) / c.DEC as DEC";
      $listobject->querystring .= "    from subluportions as a,";
      $listobject->querystring .= "         workdistro as b, ";
      $listobject->querystring .= "         monthdays as c";
      $listobject->querystring .= "    where ";
      $listobject->querystring .= "        b.spreadid = 6";
      $listobject->querystring .= "    and c.spreadid = 4";
      $listobject->querystring .= "    and b.landuseid = a.landuseid";
      $listobject->performQuery();

      $listobject->querystring = "update cropneedapplied set landuseid = a.luid ";
      $listobject->querystring .= "    from worklanduses as a ";
      $listobject->querystring .= "    where cropneedapplied.landuseid = a.planduseid ";
      $listobject->querystring .= "       and a.planduseid = a.landuseid ";
      $listobject->performQuery();


      $listobject->querystring = "create temp table cropneedtotal as select ";
      $listobject->querystring .= "a.subshedid, a.sublu, a.landuseid, a.pollutanttype, ";
      $listobject->querystring .= "0.0 as annualapplied ,";
      $listobject->querystring .= "a.JAN*b.JAN as JAN,";
      $listobject->querystring .= "a.FEB*b.FEB as FEB,";
      $listobject->querystring .= "a.MAR*b.MAR as MAR,";
      $listobject->querystring .= "a.APR*b.APR as APR,";
      $listobject->querystring .= "a.MAY*b.MAY as MAY,";
      $listobject->querystring .= "a.JUN*b.JUN as JUN,";
      $listobject->querystring .= "a.JUL*b.JUL as JUL,";
      $listobject->querystring .= "a.AUG*b.AUG as AUG,";
      $listobject->querystring .= "a.SEP*b.SEP as SEP,";
      $listobject->querystring .= "a.OCT*b.OCT as OCT,";
      $listobject->querystring .= "a.NOV*b.NOV as NOV,";
      $listobject->querystring .= "a.DEC*b.DEC as DEC";
      $listobject->querystring .= "    from cropneedapplied as a, ";
      $listobject->querystring .= "         monthdays as b ";
      $listobject->performQuery();


      $listobject->querystring = "update cropneedtotal set annualapplied = ";
      $listobject->querystring .= "( JAN +";
      $listobject->querystring .= "FEB + ";
      $listobject->querystring .= "MAR + ";
      $listobject->querystring .= "APR + ";
      $listobject->querystring .= "MAY + ";
      $listobject->querystring .= "JUN + ";
      $listobject->querystring .= "JUL + ";
      $listobject->querystring .= "AUG + ";
      $listobject->querystring .= "SEP + ";
      $listobject->querystring .= "OCT + ";
      $listobject->querystring .= "NOV + ";
      $listobject->querystring .= "DEC )";
      $listobject->performQuery();


      $listobject->debug = $prevdebug;

   }


 function makeMonStorageApplied($listobject, $projectid, $overwrite, $debug) {

      # creates a table of all daily load production that goes to a destination landuse
      # this includes everything but the storge landuse which goes into a separate
      # routine.
      if ($listobject->tableExists('monstorageapplied') and !$overwrite) {
         print("<b>Warning:</b>Table monstored already exists. Will not overwrite<br>");
         return;
      }
      if ( !($listobject->tableExists('annualstored')) ) {
         makeMonStored($listobject, $projectid, $overwrite, $debug);
      }

      $prevdebug = $listobject->debug;
      $listobject->debug = $debug;

      $listobject->querystring = "create temp table monstorageapplied as select a.subshedid, ";
      $listobject->querystring .= "b.landuseid, a.sourceid, a.sourceclass, ";
      $listobject->querystring .= "a.sourcetypeid, a.pollutanttype, a.typeid, ";
      $listobject->querystring .= " a.annualstored, a.annualapplied, ";
      $listobject->querystring .= "a.annualdieoff, a.annualvolatilized, ";
      $listobject->querystring .= "(b.JAN * a.annualapplied) / c.JAN as JAN, ";
      $listobject->querystring .= "(b.FEB * a.annualapplied) / c.FEB as FEB, ";
      $listobject->querystring .= "(b.MAR * a.annualapplied) / c.MAR as MAR, ";
      $listobject->querystring .= "(b.APR * a.annualapplied) / c.APR as APR,";
      $listobject->querystring .= "(b.MAY * a.annualapplied) / c.MAY as MAY, ";
      $listobject->querystring .= "(b.JUN * a.annualapplied) / c.JUN as JUN, ";
      $listobject->querystring .= "(b.JUL * a.annualapplied) / c.JUL as JUL, ";
      $listobject->querystring .= "(b.AUG * a.annualapplied) / c.AUG as AUG, ";
      $listobject->querystring .= "(b.SEP * a.annualapplied) / c.SEP as SEP, ";
      $listobject->querystring .= "(b.OCT * a.annualapplied) / c.OCT as OCT, ";
      $listobject->querystring .= "(b.NOV * a.annualapplied) / c.NOV as NOV, ";
      $listobject->querystring .= "(b.DEC * a.annualapplied) / c.DEC as DEC";
      $listobject->querystring .= "    from annualstored as a,";
      $listobject->querystring .= "         workdistro as b,  ";
      $listobject->querystring .= "         monthdays as c";
      $listobject->querystring .= "    where b.sourceid = a.sourceid";
      $listobject->querystring .= "    and b.spreadid = 2";
      $listobject->querystring .= "    and c.spreadid = 4";
      $listobject->querystring .= "    and b.subshedid = a.subshedid";
      $listobject->performQuery();

      $listobject->debug = $prevdebug;

   }


   function totalNonStored($listobject, $projectid, $overwrite, $debug) {

      # creates a table of all daily load production that goes to a destination landuse
      # this includes everything but the storge landuse which goes into a separate
      # routine.
      if ($listobject->tableExists('allnonstored') and !$overwrite) {
         print("<b>Warning:</b>Table allnonstored already exists. Will not overwrite<br>");
         return;
      }
      if ( !($listobject->tableExists('monapplied')) ) {
         makeMonApplied($listobject, $projectid, $overwrite, $debug);
      }

      $prevdebug = $listobject->debug;
      $listobject->debug = $debug;



      $listobject->querystring = "create temp table allnonstored as select ";
      $listobject->querystring .= "a.subshedid, a.landuseid, a.pollutanttype, ";
      $listobject->querystring .= "0.0 as annualapplied, ";
      $listobject->querystring .= "sum(a.JAN*b.JAN) as JAN,";
      $listobject->querystring .= "sum(a.FEB*b.FEB) as FEB,";
      $listobject->querystring .= "sum(a.MAR*b.MAR) as MAR,";
      $listobject->querystring .= "sum(a.APR*b.APR) as APR,";
      $listobject->querystring .= "sum(a.MAY*b.MAY) as MAY,";
      $listobject->querystring .= "sum(a.JUN*b.JUN) as JUN,";
      $listobject->querystring .= "sum(a.JUL*b.JUL) as JUL,";
      $listobject->querystring .= "sum(a.AUG*b.AUG) as AUG,";
      $listobject->querystring .= "sum(a.SEP*b.SEP) as SEP,";
      $listobject->querystring .= "sum(a.OCT*b.OCT) as OCT,";
      $listobject->querystring .= "sum(a.NOV*b.NOV) as NOV,";
      $listobject->querystring .= "sum(a.DEC*b.DEC) as DEC";
      $listobject->querystring .= "    from monapplied as a, ";
      $listobject->querystring .= "         monthdays as b ";
      $listobject->querystring .= "    where ";
      $listobject->querystring .= "        a.landuseid not in (select luid from worklanduses ";
      $listobject->querystring .= "           where landusetype in (6,7,8) )";
      $listobject->querystring .= "   group by a.subshedid, a.landuseid, a.pollutanttype";
      $listobject->performQuery();


      $listobject->querystring = "update allnonstored set annualapplied = ";
      $listobject->querystring .= "( JAN +";
      $listobject->querystring .= "FEB + ";
      $listobject->querystring .= "MAR + ";
      $listobject->querystring .= "APR + ";
      $listobject->querystring .= "MAY + ";
      $listobject->querystring .= "JUN + ";
      $listobject->querystring .= "JUL + ";
      $listobject->querystring .= "AUG + ";
      $listobject->querystring .= "SEP + ";
      $listobject->querystring .= "OCT + ";
      $listobject->querystring .= "NOV + ";
      $listobject->querystring .= "DEC )";
      $listobject->performQuery();
      $listobject->debug = $prevdebug;

   }

   function sumAllMonAppliedLoads($listobject, $projectid, $overwrite, $debug) {

      # creates a table of all daily load production that goes to a destination landuse
      # this includes everything including the storge landuse

      if ($listobject->tableExists('allmonapplied') and !$overwrite) {
         print("<b>Warning:</b>Table monstored already exists. Will not overwrite<br>");
         return;
      }
      if ( !($listobject->tableExists('monstorageapplied')) ) {
         makeMonStorageApplied($listobject, $projectid, $overwrite, $debug);
      }

      $prevdebug = $listobject->debug;
      $listobject->debug = $debug;


      $listobject->querystring = "create temp table allmonapplied as select a.subshedid, ";
      $listobject->querystring .= "a.landuseid, a.sourceid, a.sourceclass, a.pollutanttype, ";
      $listobject->querystring .= "a.JAN, ";
      $listobject->querystring .= "a.FEB, ";
      $listobject->querystring .= "a.MAR, ";
      $listobject->querystring .= "a.APR, ";
      $listobject->querystring .= "a.MAY, ";
      $listobject->querystring .= "a.JUN, ";
      $listobject->querystring .= "a.JUL, ";
      $listobject->querystring .= "a.AUG, ";
      $listobject->querystring .= "a.SEP, ";
      $listobject->querystring .= "a.OCT, ";
      $listobject->querystring .= "a.NOV, ";
      $listobject->querystring .= "a.DEC ";
      $listobject->querystring .= "    from monapplied as a";
      $listobject->querystring .= "    where ";
      /*
      # OLD SCHOOL
      $listobject->querystring .= "        landuseid not in (select luid from worklanduses where ";
      $listobject->querystring .= "           landusetype in (6,7,8) )";
      */
      # NEW SCHOOL
      $listobject->querystring .= "        landuseid in (select luid from worklanduses where ";
      $listobject->querystring .= "           landusetype not in (6,7,8) )";
      $listobject->performQuery();


      $listobject->querystring = "insert into allmonapplied (subshedid, landuseid, sourceid, sourceclass, pollutanttype, ";
      $listobject->querystring .= "JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC) ";
      $listobject->querystring .= " select a.subshedid, ";
      $listobject->querystring .= "a.landuseid, a.sourceid, a.sourceclass, a.pollutanttype, ";
      $listobject->querystring .= "a.JAN, ";
      $listobject->querystring .= "a.FEB, ";
      $listobject->querystring .= "a.MAR, ";
      $listobject->querystring .= "a.APR, ";
      $listobject->querystring .= "a.MAY, ";
      $listobject->querystring .= "a.JUN, ";
      $listobject->querystring .= "a.JUL, ";
      $listobject->querystring .= "a.AUG, ";
      $listobject->querystring .= "a.SEP, ";
      $listobject->querystring .= "a.OCT, ";
      $listobject->querystring .= "a.NOV, ";
      $listobject->querystring .= "a.DEC ";
      $listobject->querystring .= "    from monstorageapplied as a";
      $listobject->performQuery();


      if ( ($listobject->tableExists('cropneedapplied')) ) {
         $listobject->querystring = "insert into allmonapplied (subshedid, landuseid, sourceid, sourceclass, pollutanttype, ";
         $listobject->querystring .= "JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC) ";
         $listobject->querystring .= " select a.subshedid, ";
         $listobject->querystring .= "a.landuseid, a.sourceid, a.sourceclass, a.pollutanttype, ";
         $listobject->querystring .= "a.JAN, ";
         $listobject->querystring .= "a.FEB, ";
         $listobject->querystring .= "a.MAR, ";
         $listobject->querystring .= "a.APR, ";
         $listobject->querystring .= "a.MAY, ";
         $listobject->querystring .= "a.JUN, ";
         $listobject->querystring .= "a.JUL, ";
         $listobject->querystring .= "a.AUG, ";
         $listobject->querystring .= "a.SEP, ";
         $listobject->querystring .= "a.OCT, ";
         $listobject->querystring .= "a.NOV, ";
         $listobject->querystring .= "a.DEC ";
         $listobject->querystring .= "    from cropneedapplied as a";
         $listobject->performQuery();
      }


      if ( ($listobject->tableExists('nutmanapplied')) ) {
         $listobject->querystring = "insert into allmonapplied (subshedid, landuseid, sourceid, sourceclass, pollutanttype, ";
         $listobject->querystring .= "JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC) ";
         $listobject->querystring .= " select a.subshedid, ";
         $listobject->querystring .= "a.landuseid, a.sourceid, a.sourceclass, a.pollutanttype, ";
         $listobject->querystring .= "a.JAN, ";
         $listobject->querystring .= "a.FEB, ";
         $listobject->querystring .= "a.MAR, ";
         $listobject->querystring .= "a.APR, ";
         $listobject->querystring .= "a.MAY, ";
         $listobject->querystring .= "a.JUN, ";
         $listobject->querystring .= "a.JUL, ";
         $listobject->querystring .= "a.AUG, ";
         $listobject->querystring .= "a.SEP, ";
         $listobject->querystring .= "a.OCT, ";
         $listobject->querystring .= "a.NOV, ";
         $listobject->querystring .= "a.DEC ";
         $listobject->querystring .= "    from nutmanapplied as a";
         $listobject->performQuery();
      }

      $listobject->querystring = "create temp table sumallmonapplied as select ";
      $listobject->querystring .= "a.subshedid, a.landuseid, a.pollutanttype, ";
      $listobject->querystring .= "sum(a.JAN) as JAN,";
      $listobject->querystring .= "sum(a.FEB) as FEB,";
      $listobject->querystring .= "sum(a.MAR) as MAR,";
      $listobject->querystring .= "sum(a.APR) as APR,";
      $listobject->querystring .= "sum(a.MAY) as MAY,";
      $listobject->querystring .= "sum(a.JUN) as JUN,";
      $listobject->querystring .= "sum(a.JUL) as JUL,";
      $listobject->querystring .= "sum(a.AUG) as AUG,";
      $listobject->querystring .= "sum(a.SEP) as SEP,";
      $listobject->querystring .= "sum(a.OCT) as OCT,";
      $listobject->querystring .= "sum(a.NOV) as NOV,";
      $listobject->querystring .= "sum(a.DEC) as DEC ";
      $listobject->querystring .= "    from allmonapplied as a";
      $listobject->querystring .= "    group by a.subshedid, a.landuseid, a.pollutanttype";
      $listobject->performQuery();

      $listobject->debug = $prevdebug;

   }


   function sumAllMonAppliedLoads2($listobject, $projectid, $overwrite, $montables, $debug) {

      # creates a table of all daily load production that goes to a destination landuse
      # this includes everything including the storge landuse

      $i = 1;

      if ($listobject->tableExists('allmonapplied')) {

         $i = 2;
         if ($overwrite) {
            # enabling the 'drop table' mode seems to act more efficiently in
            # postgreSQL, however, the 'delete from' mode is the preferred mode
            # to be used in the Chesapeake Bay Office SIMS SQLServer database.
            # The understanding is that the DB admins feel that there is too much
            # overhead incurred by dropping and creating tables, however, what I am
            # finding in PostgreSQL is that the numbers of records involved leaves a
            # bunch of deleted records that should be vaccuumed out to increase efficiency
            $listobject->querystring = "drop table allmonapplied";
#            $listobject->querystring = "delete from allmonapplied";
            $listobject->performQuery();
            $listobject->querystring = "drop table sumallmonapplied";
#            $listobject->querystring = "delete from sumallmonapplied";
            $listobject->performQuery();
            $i = 1;
         }
      }

      $prevdebug = $listobject->debug;
      $listobject->debug = $debug;



      foreach ($montables as $thistable) {
/*         if ($i == 1) {
   */
         if (!$listobject->tableExists('allmonapplied')) {

            $listobject->querystring = "create temp table allmonapplied as select ";
            $listobject->querystring .= " a.subshedid, a.landuseid, a.sourceid, a.luname, ";
            $listobject->querystring .= "a.sourceclass, a.pollutanttype, a.spreadid, ";
            $listobject->querystring .= "(a.JAN + a.FEB + a.MAR + a.APR + a.MAY + ";
            $listobject->querystring .= "a.JUN + a.JUL + a.AUG + a.SEP + a.OCT + ";
            $listobject->querystring .= "a.NOV + a.DEC)/12.0 as annualapplied, ";
            $listobject->querystring .= "a.JAN, ";
            $listobject->querystring .= "a.FEB, ";
            $listobject->querystring .= "a.MAR, ";
            $listobject->querystring .= "a.APR, ";
            $listobject->querystring .= "a.MAY, ";
            $listobject->querystring .= "a.JUN, ";
            $listobject->querystring .= "a.JUL, ";
            $listobject->querystring .= "a.AUG, ";
            $listobject->querystring .= "a.SEP, ";
            $listobject->querystring .= "a.OCT, ";
            $listobject->querystring .= "a.NOV, ";
            $listobject->querystring .= "a.DEC ";
            $listobject->querystring .= "    from $thistable as a";
            $listobject->querystring .= "    where ";
            /*
            # OLD SCHOOL
            $listobject->querystring .= "        landuseid not in (select luid from worklanduses where ";
            $listobject->querystring .= "           landusetype in (6,7,8) )";
            */
            # NEW SCHOOL
            $listobject->querystring .= "        landuseid in (select luid from worklanduses where ";
            $listobject->querystring .= "           landusetype not in (6,7,8) )";
            $listobject->performQuery();
         } else {
            $listobject->querystring = "insert into allmonapplied (subshedid, landuseid, ";
            $listobject->querystring .= "sourceid, luname, sourceclass, pollutanttype, ";
            $listobject->querystring .= "spreadid, annualapplied, ";
            $listobject->querystring .= "JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, ";
            $listobject->querystring .= "OCT, NOV, DEC) ";
            $listobject->querystring .= " select a.subshedid, a.landuseid, a.sourceid, ";
            $listobject->querystring .= "a.luname, a.sourceclass, a.pollutanttype, ";
            $listobject->querystring .= "a.spreadid, ";
            $listobject->querystring .= "(a.JAN + a.FEB + a.MAR + a.APR + a.MAY + a.JUN + ";
            $listobject->querystring .= "      a.JUL + a.AUG + a.SEP + a.OCT + a.NOV ";
            $listobject->querystring .= "      + a.DEC)/12.0 as annualapplied, ";
            $listobject->querystring .= "a.JAN, ";
            $listobject->querystring .= "a.FEB, ";
            $listobject->querystring .= "a.MAR, ";
            $listobject->querystring .= "a.APR, ";
            $listobject->querystring .= "a.MAY, ";
            $listobject->querystring .= "a.JUN, ";
            $listobject->querystring .= "a.JUL, ";
            $listobject->querystring .= "a.AUG, ";
            $listobject->querystring .= "a.SEP, ";
            $listobject->querystring .= "a.OCT, ";
            $listobject->querystring .= "a.NOV, ";
            $listobject->querystring .= "a.DEC ";
            $listobject->querystring .= "    from $thistable as a";
            $listobject->performQuery();
         }
         $i++;
      }


#      if (!$listobject->tableExists('sumallmonapplied')) {

      if ($listobject->tableExists('sumallmonapplied')) {
         $listobject->querystring = "drop table sumallmonapplied";
         $listobject->performQuery();
      }

      $listobject->querystring = "create temp table sumallmonapplied as select ";
      $listobject->querystring .= "a.subshedid, a.landuseid, a.pollutanttype, a.luname, ";
      $listobject->querystring .= "sum(a.JAN + a.FEB + a.MAR + a.APR + a.MAY + ";
      $listobject->querystring .= "   a.JUN + a.JUL + a.AUG + a.SEP + a.OCT + ";
      $listobject->querystring .= "   a.NOV + a.DEC) as annualapplied, ";
      $listobject->querystring .= "sum(a.JAN) as JAN,";
      $listobject->querystring .= "sum(a.FEB) as FEB,";
      $listobject->querystring .= "sum(a.MAR) as MAR,";
      $listobject->querystring .= "sum(a.APR) as APR,";
      $listobject->querystring .= "sum(a.MAY) as MAY,";
      $listobject->querystring .= "sum(a.JUN) as JUN,";
      $listobject->querystring .= "sum(a.JUL) as JUL,";
      $listobject->querystring .= "sum(a.AUG) as AUG,";
      $listobject->querystring .= "sum(a.SEP) as SEP,";
      $listobject->querystring .= "sum(a.OCT) as OCT,";
      $listobject->querystring .= "sum(a.NOV) as NOV,";
      $listobject->querystring .= "sum(a.DEC) as DEC ";
      $listobject->querystring .= "    from allmonapplied as a";
      $listobject->querystring .= "    group by a.subshedid, a.landuseid, a.luname, a.pollutanttype";
      $listobject->performQuery();



      $listobject->debug = $prevdebug;
   }


function sumByDistro($listobject, $projectid, $overwrite, $debug) {

      if ($listobject->tableExists('sumbyludistro')) {
         $listobject->querystring = "drop table sumbyludistro";
         $listobject->performQuery();
      }

      $listobject->querystring = "create temp table sumbyludistro as select ";
      $listobject->querystring .= "a.subshedid, a.landuseid, a.pollutanttype, a.spreadid, ";
      $listobject->querystring .= "sum(a.JAN*b.JAN + a.FEB*b.FEB + a.MAR*b.MAR + a.APR*b.APR + a.MAY*b.MAY + a.JUN*b.JUN + a.JUL*b.JUL + a.AUG*b.AUG + a.SEP*b.SEP + a.OCT*b.OCT + a.NOV*b.NOV + a.DEC*b.DEC) as annualapplied, ";
      $listobject->querystring .= "sum(a.JAN*b.JAN) as JAN,";
      $listobject->querystring .= "sum(a.FEB*b.FEB) as FEB,";
      $listobject->querystring .= "sum(a.MAR*b.MAR) as MAR,";
      $listobject->querystring .= "sum(a.APR*b.APR) as APR,";
      $listobject->querystring .= "sum(a.MAY*b.MAY) as MAY,";
      $listobject->querystring .= "sum(a.JUN*b.JUN) as JUN,";
      $listobject->querystring .= "sum(a.JUL*b.JUL) as JUL,";
      $listobject->querystring .= "sum(a.AUG*b.AUG) as AUG,";
      $listobject->querystring .= "sum(a.SEP*b.SEP) as SEP,";
      $listobject->querystring .= "sum(a.OCT*b.OCT) as OCT,";
      $listobject->querystring .= "sum(a.NOV*b.NOV) as NOV,";
      $listobject->querystring .= "sum(a.DEC*b.DEC) as DEC";
      $listobject->querystring .= "    from allmonapplied as a, ";
      $listobject->querystring .= "         monthdays as b ";
      $listobject->querystring .= "    group by a.subshedid, a.landuseid, a.pollutanttype, a.spreadid";
      $listobject->performQuery();

      if ($listobject->tableExists('sumbydistro')) {
         $listobject->querystring = "drop table sumbydistro";
         $listobject->performQuery();
      }

      $listobject->querystring = "create temp table sumbydistro as select ";
      $listobject->querystring .= "a.subshedid, a.pollutanttype, a.spreadid, ";
      $listobject->querystring .= "sum(a.JAN*b.JAN + a.FEB*b.FEB + a.MAR*b.MAR + a.APR*b.APR + a.MAY*b.MAY + a.JUN*b.JUN + a.JUL*b.JUL + a.AUG*b.AUG + a.SEP*b.SEP + a.OCT*b.OCT + a.NOV*b.NOV + a.DEC*b.DEC) as annualapplied, ";
      $listobject->querystring .= "sum(a.JAN*b.JAN) as JAN,";
      $listobject->querystring .= "sum(a.FEB*b.FEB) as FEB,";
      $listobject->querystring .= "sum(a.MAR*b.MAR) as MAR,";
      $listobject->querystring .= "sum(a.APR*b.APR) as APR,";
      $listobject->querystring .= "sum(a.MAY*b.MAY) as MAY,";
      $listobject->querystring .= "sum(a.JUN*b.JUN) as JUN,";
      $listobject->querystring .= "sum(a.JUL*b.JUL) as JUL,";
      $listobject->querystring .= "sum(a.AUG*b.AUG) as AUG,";
      $listobject->querystring .= "sum(a.SEP*b.SEP) as SEP,";
      $listobject->querystring .= "sum(a.OCT*b.OCT) as OCT,";
      $listobject->querystring .= "sum(a.NOV*b.NOV) as NOV,";
      $listobject->querystring .= "sum(a.DEC*b.DEC) as DEC";
      $listobject->querystring .= "    from allmonapplied as a, ";
      $listobject->querystring .= "         monthdays as b ";
      $listobject->querystring .= "    group by a.subshedid, a.pollutanttype, a.spreadid";
      $listobject->performQuery();

      $listobject->debug = $prevdebug;

   }


   function sumAllStored($listobject, $projectid, $overwrite, $montables, $debug) {

      # creates a table of all daily load production that goes to a destination landuse
      # this includes everything including the storge landuse

      if ($listobject->tableExists('allstored')) {
         if (!$overwrite) {
            print("<b>Warning:</b>Table allstored already exists. Will not overwrite<br>");
            return;
         } else {
            $listobject->querystring = "drop table allstored";
            $listobject->performQuery();
         }
      }

      $prevdebug = $listobject->debug;
      $listobject->debug = $debug;

      $i = 1;

      foreach ($montables as $thistable) {

         if ($i == 1) {
            $listobject->querystring = "create temp table allstored as select a.subshedid, ";
            $listobject->querystring .= "a.landuseid, a.sourceid, a.sourceclass, a.pollutanttype, ";
            $listobject->querystring .= "a.annualstored, ";
            $listobject->querystring .= "a.annualapplied, ";
            $listobject->querystring .= "a.annualvolatilized, ";
            $listobject->querystring .= "a.annualdieoff ";
            $listobject->querystring .= "    from $thistable as a";
            $listobject->performQuery();
         } else {

            $listobject->querystring = "insert into allstored (subshedid, landuseid, sourceid, sourceclass, pollutanttype, ";
            $listobject->querystring .= "annualstored, annualapplied, annualvolatilized, annualdieoff) ";
            $listobject->querystring .= " select a.subshedid, ";
            $listobject->querystring .= "a.landuseid, a.sourceid, a.sourceclass, a.pollutanttype, ";
            $listobject->querystring .= "a.annualstored, ";
            $listobject->querystring .= "a.annualapplied, ";
            $listobject->querystring .= "a.annualvolatilized, ";
            $listobject->querystring .= "a.annualdieoff ";
            $listobject->querystring .= "    from $thistable as a";
            $listobject->performQuery();
         }
         $i++;
      }

      $listobject->debug = $prevdebug;

   }

   function createLanduseMap($listobject, $projectid, $overwrite, $debug) {

      # creates a table of all daily load production that goes to a destination landuse
      # this includes everything but the storge landuse which goes into a separate
      # routine.
      if ($listobject->tableExists('landusemap') and !$overwrite) {
         print("<b>Warning:</b>Table monstored already exists. Will not overwrite<br>");
         return;
      }

      $prevdebug = $listobject->debug;
      $listobject->debug = $debug;

      $listobject->querystring = "create temp table landusemap as ";
      $listobject->querystring .= "select b.subshedid, b.sublu, a.luid as landuseid, b.luarea ";
      $listobject->querystring .= "from worklanduses as a, worksublu as b ";
      $listobject->querystring .= "   where a.hspflu = b.luname";
      $listobject->performQuery();

      $listobject->debug = $prevdebug;
   }

   function createMonPerUnitArea($listobject, $projectid, $overwrite, $debug) {

      # creates a table of all daily load production that goes to a destination landuse
      # this includes everything but the storge landuse which goes into a separate
      # routine.
      if ($listobject->tableExists('monperunitarea') ) {
         if (!$overwrite) {
            print("<b>Warning:</b>Table monperunitarea already exists. Will not overwrite<br>");
            return;
         } else {
            # enabling the 'drop table' mode seems to act more efficiently in
            # postgreSQL, however, the 'delete from' mode is the preferred mode
            # to be used in the Chesapeake Bay Office SIMS SQLServer database.
            # The understanding is that the DB admins feel that there is too much
            # overhead incurred by dropping and creating tables, however, what I am
            # finding in PostgreSQL is that the numbers of records involved leaves a
            # bunch of deleted records that should be vaccuumed out to increase efficiency

#            $listobject->querystring = "drop table monperunitarea ";

            $listobject->querystring = "delete from monperunitarea ";
            $listobject->performQuery();

            $listobject->querystring = "drop table nonspread_lbs ";
            $listobject->performQuery();
            $listobject->querystring = "drop table sourceperunitarea ";
            $listobject->performQuery();
            $listobject->querystring = "drop table montotal ";
            $listobject->performQuery();
            $listobject->querystring = "drop table monsourceperunitarea ";
            $listobject->performQuery();

         }
      }

      if ( !($listobject->tableExists('sumallmonapplied')) ) {
         $tbls = array('monapplied');
         sumAllMonAppliedLoads2($listobject, $projectid, $overwrite, $tbls, $debug);
      }
      if ( !($listobject->tableExists('landusemap')) ) {
         createLanduseMap($listobject, $projectid, $overwrite, $debug);
      }

      $prevdebug = $listobject->debug;
      $listobject->debug = $debug;


      # the daily rate of aplication per unit area
      if (!$listobject->tableExists('monperunitarea') ) {
         $listobject->querystring = "create temp table monperunitarea as select ";
         $listobject->querystring .= "a.subshedid, b.sublu, b.luname, b.luarea, a.landuseid, a.pollutanttype, ";
         $listobject->querystring .= "b.maxp, b.maxn, (b.luarea * b.maxp) as pcap, ";
         $listobject->querystring .= " (b.luarea * b.maxn) as ncap, b.optp, b.optn, ";
         $listobject->querystring .= " b.nrate, b.prate, b.uptake_n, uptake_p, ";
         $listobject->querystring .= "a.annualapplied/b.luarea as annualapplied, ";
         $listobject->querystring .= "a.JAN/b.luarea as JAN, ";
         $listobject->querystring .= "a.FEB/b.luarea as FEB, ";
         $listobject->querystring .= "a.MAR/b.luarea as MAR, ";
         $listobject->querystring .= "a.APR/b.luarea as APR, ";
         $listobject->querystring .= "a.MAY/b.luarea as MAY, ";
         $listobject->querystring .= "a.JUN/b.luarea as JUN, ";
         $listobject->querystring .= "a.JUL/b.luarea as JUL, ";
         $listobject->querystring .= "a.AUG/b.luarea as AUG, ";
         $listobject->querystring .= "a.SEP/b.luarea as SEP, ";
         $listobject->querystring .= "a.OCT/b.luarea as OCT, ";
         $listobject->querystring .= "a.NOV/b.luarea as NOV, ";
         $listobject->querystring .= "a.DEC/b.luarea as DEC  ";
         $listobject->querystring .= "    from sumallmonapplied as a, ";
         $listobject->querystring .= "         worksublu as b ";
# trying to eliminate use of mapping table worklanduses
#         $listobject->querystring .= "         worklanduses as c ";
         $listobject->querystring .= "    where a.subshedid = b.subshedid ";
         $listobject->querystring .= "       and b.luname = a.luname ";
# trying to eliminate use of mapping table worklanduses
#         $listobject->querystring .= "       and b.luname = c.hspflu ";
#         $listobject->querystring .= "       and a.landuseid = c.luid ";
         $listobject->querystring .= "       and b.luarea > 0 ";
#         print("$listobject->querystring ; <br>");
         $listobject->performQuery();
      } else {
         $listobject->querystring = "insert into monperunitarea (subshedid, sublu, luname, ";
         $listobject->querystring .= " luarea, landuseid, pollutanttype, uptake_p, ";
         $listobject->querystring .= " nrate, prate, uptake_n, maxp, maxn, optp, optn, ";
         $listobject->querystring .= " pcap, ncap, annualapplied, JAN, FEB, MAR, APR, ";
         $listobject->querystring .= " MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC) ";
         $listobject->querystring .= " select a.subshedid, b.sublu, b.luname, b.luarea, ";
         $listobject->querystring .= " a.landuseid, a.pollutanttype, b.uptake_p, ";
         $listobject->querystring .= " b.nrate, b.prate, b.uptake_n, ";
         $listobject->querystring .= "b.maxp, b.maxn, b.optp, b.optn, b.luarea * b.maxp as pcap, ";
         $listobject->querystring .= "b.luarea * b.maxn as ncap, ";
         $listobject->querystring .= "a.annualapplied/b.luarea as annualapplied, ";
         $listobject->querystring .= "a.JAN/b.luarea as JAN, ";
         $listobject->querystring .= "a.FEB/b.luarea as FEB, ";
         $listobject->querystring .= "a.MAR/b.luarea as MAR, ";
         $listobject->querystring .= "a.APR/b.luarea as APR, ";
         $listobject->querystring .= "a.MAY/b.luarea as MAY, ";
         $listobject->querystring .= "a.JUN/b.luarea as JUN, ";
         $listobject->querystring .= "a.JUL/b.luarea as JUL, ";
         $listobject->querystring .= "a.AUG/b.luarea as AUG, ";
         $listobject->querystring .= "a.SEP/b.luarea as SEP, ";
         $listobject->querystring .= "a.OCT/b.luarea as OCT, ";
         $listobject->querystring .= "a.NOV/b.luarea as NOV, ";
         $listobject->querystring .= "a.DEC/b.luarea as DEC  ";
         $listobject->querystring .= "    from sumallmonapplied as a, ";
         $listobject->querystring .= "         worksublu as b ";
# trying to eliminate use of mapping table worklanduses
#         $listobject->querystring .= "         worklanduses as c ";
         $listobject->querystring .= "    where a.subshedid = b.subshedid ";
         $listobject->querystring .= "       and a.luname = b.luname ";
# trying to eliminate use of mapping table worklanduses
#         $listobject->querystring .= "       and b.luname = c.hspflu ";
#         $listobject->querystring .= "       and a.landuseid = c.luid ";
         $listobject->querystring .= "       and b.luarea > 0 ";
#         print("$listobject->querystring ; <br>");
         $listobject->performQuery();
      }


      # create a table of mass/unit area-day applications by source
      $listobject->querystring = "create temp table sourceperunitarea as select ";
      $listobject->querystring .= "a.subshedid, b.sublu, b.luname, b.luarea, a.landuseid, a.pollutanttype, ";
      $listobject->querystring .= " a.sourceid, a.sourceclass, a.spreadid, ";
      $listobject->querystring .= "b.maxp, b.maxn , b.luarea * b.maxp as pcap, ";
      $listobject->querystring .= "b.luarea * b.maxn as ncap, ";
      $listobject->querystring .= "a.annualapplied/b.luarea as annualapplied, ";
      $listobject->querystring .= "a.JAN/b.luarea as JAN, ";
      $listobject->querystring .= "a.FEB/b.luarea as FEB, ";
      $listobject->querystring .= "a.MAR/b.luarea as MAR, ";
      $listobject->querystring .= "a.APR/b.luarea as APR, ";
      $listobject->querystring .= "a.MAY/b.luarea as MAY, ";
      $listobject->querystring .= "a.JUN/b.luarea as JUN, ";
      $listobject->querystring .= "a.JUL/b.luarea as JUL, ";
      $listobject->querystring .= "a.AUG/b.luarea as AUG, ";
      $listobject->querystring .= "a.SEP/b.luarea as SEP, ";
      $listobject->querystring .= "a.OCT/b.luarea as OCT, ";
      $listobject->querystring .= "a.NOV/b.luarea as NOV, ";
      $listobject->querystring .= "a.DEC/b.luarea as DEC  ";
      $listobject->querystring .= "    from allmonapplied as a, ";
      $listobject->querystring .= "         worksublu as b ";
# trying to eliminate use of mapping table worklanduses
#      $listobject->querystring .= "         worklanduses as c ";
      $listobject->querystring .= "    where a.subshedid = b.subshedid ";
      $listobject->querystring .= "       and b.luname = a.luname ";
# trying to eliminate use of mapping table worklanduses
#      $listobject->querystring .= "       and b.luname = c.hspflu ";
#      $listobject->querystring .= "       and a.landuseid = c.luid ";
      $listobject->querystring .= "       and b.luarea > 0 ";
#         print("$listobject->querystring ; <br>");
      $listobject->performQuery();


      # a summary of mass/unit area applied by each different source on each land-use
      # in a given month
      $listobject->querystring = "create temp table monsourceperunitarea as select ";
      $listobject->querystring .= "a.subshedid, a.sublu, a.sourceid, a.sourceclass, ";
      $listobject->querystring .= "a.pollutanttype,  a.spreadid, a.landuseid, a.luname, a.luarea, ";
      $listobject->querystring .= " 0.0 as annualapplied, a.maxp, a.maxn, a.pcap, a.ncap, ";
      $listobject->querystring .= "a.JAN*b.JAN as JAN,";
      $listobject->querystring .= "a.FEB*b.FEB as FEB,";
      $listobject->querystring .= "a.MAR*b.MAR as MAR,";
      $listobject->querystring .= "a.APR*b.APR as APR,";
      $listobject->querystring .= "a.MAY*b.MAY as MAY,";
      $listobject->querystring .= "a.JUN*b.JUN as JUN,";
      $listobject->querystring .= "a.JUL*b.JUL as JUL,";
      $listobject->querystring .= "a.AUG*b.AUG as AUG,";
      $listobject->querystring .= "a.SEP*b.SEP as SEP,";
      $listobject->querystring .= "a.OCT*b.OCT as OCT,";
      $listobject->querystring .= "a.NOV*b.NOV as NOV,";
      $listobject->querystring .= "a.DEC*b.DEC as DEC";
      $listobject->querystring .= "    from sourceperunitarea as a, ";
      $listobject->querystring .= "         monthdays as b ";
#         print("$listobject->querystring ; <br>");
      $listobject->performQuery();


      $listobject->querystring = "update monsourceperunitarea set annualapplied = ";
      $listobject->querystring .= "( JAN +";
      $listobject->querystring .= "FEB + ";
      $listobject->querystring .= "MAR + ";
      $listobject->querystring .= "APR + ";
      $listobject->querystring .= "MAY + ";
      $listobject->querystring .= "JUN + ";
      $listobject->querystring .= "JUL + ";
      $listobject->querystring .= "AUG + ";
      $listobject->querystring .= "SEP + ";
      $listobject->querystring .= "OCT + ";
      $listobject->querystring .= "NOV + ";
      $listobject->querystring .= "DEC )";
      $listobject->performQuery();

      $listobject->querystring = "create temp table nonspread_lbs as select ";
      $listobject->querystring .= "a.subshedid, b.sublu, a.landuseid, a.pollutanttype, ";
      $listobject->querystring .= "b.luarea, ";
      $listobject->querystring .= "a.JAN,";
      $listobject->querystring .= "a.FEB,";
      $listobject->querystring .= "a.MAR, ";
      $listobject->querystring .= "a.APR,";
      $listobject->querystring .= "a.MAY,";
      $listobject->querystring .= "a.JUN,";
      $listobject->querystring .= "a.JUL,";
      $listobject->querystring .= "a.AUG,";
      $listobject->querystring .= "a.SEP,";
      $listobject->querystring .= "a.OCT,";
      $listobject->querystring .= "a.NOV,";
      $listobject->querystring .= "a.DEC ";
      $listobject->querystring .= "    from sumallmonapplied as a, ";
      $listobject->querystring .= "         worksublu as b ";
# trying to eliminate use of mapping table worklanduses
#      $listobject->querystring .= "         worklanduses as c ";
      $listobject->querystring .= "    where a.subshedid = b.subshedid ";
      $listobject->querystring .= "       and b.luname = a.luname ";
# trying to eliminate use of mapping table worklanduses
#      $listobject->querystring .= "       and b.luname = c.hspflu ";
#      $listobject->querystring .= "       and a.landuseid = c.luid ";
      $listobject->querystring .= "       and b.luarea <= 0 ";
      $listobject->performQuery();


      # table with the total rate of application in units of mass/unit area per month
      $listobject->querystring = "create temp table montotal as select ";
      $listobject->querystring .= "a.subshedid, a.sublu, a.landuseid, a.pollutanttype, ";
      $listobject->querystring .= "0.0 as annualapplied, a.luname, a.luarea, ";
      $listobject->querystring .= "0.0 as totalapp, a.maxp, a.maxn, a.pcap, a.ncap, ";
      $listobject->querystring .= "a.prate, a.nrate, a.uptake_n, uptake_p, a.optn, a.optp, ";
      $listobject->querystring .= "a.JAN*b.JAN as JAN,";
      $listobject->querystring .= "a.FEB*b.FEB as FEB,";
      $listobject->querystring .= "a.MAR*b.MAR as MAR,";
      $listobject->querystring .= "a.APR*b.APR as APR,";
      $listobject->querystring .= "a.MAY*b.MAY as MAY,";
      $listobject->querystring .= "a.JUN*b.JUN as JUN,";
      $listobject->querystring .= "a.JUL*b.JUL as JUL,";
      $listobject->querystring .= "a.AUG*b.AUG as AUG,";
      $listobject->querystring .= "a.SEP*b.SEP as SEP,";
      $listobject->querystring .= "a.OCT*b.OCT as OCT,";
      $listobject->querystring .= "a.NOV*b.NOV as NOV,";
      $listobject->querystring .= "a.DEC*b.DEC as DEC";
      $listobject->querystring .= "    from monperunitarea as a, ";
      $listobject->querystring .= "         monthdays as b ";
      $listobject->performQuery();

     # print("$listobject->querystring ; <BR> ");


      $listobject->querystring = "update montotal set annualapplied = ";
      $listobject->querystring .= "( JAN +";
      $listobject->querystring .= "FEB + ";
      $listobject->querystring .= "MAR + ";
      $listobject->querystring .= "APR + ";
      $listobject->querystring .= "MAY + ";
      $listobject->querystring .= "JUN + ";
      $listobject->querystring .= "JUL + ";
      $listobject->querystring .= "AUG + ";
      $listobject->querystring .= "SEP + ";
      $listobject->querystring .= "OCT + ";
      $listobject->querystring .= "NOV + ";
      $listobject->querystring .= "DEC )";
      $listobject->performQuery();



      # insert zeroes for sublu's not already applied to
      /*
      $listobject->querystring = "insert into montotal (subshedid, sublu, landuseid, ";
      $listobject->querystring .= " pollutanttype, annualapplied, luname, luarea, ";
      $listobject->querystring .= " totalapp, maxp, maxn, pcap, ncap, ";
      $listobject->querystring .= " JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, ";
      $listobject->querystring .= " NOV, DEC) ";
      $listobject->querystring .= " select ";
      $listobject->querystring .= "b.subshedid, b.sublu, b.luname, b.luarea, c.luid, a.pollutanttype, ";
      $listobject->querystring .= "b.maxp, b.maxn , b.luarea * b.maxp as pcap, ";
      $listobject->querystring .= "b.luarea * b.maxn as ncap, ";
      $listobject->querystring .= "0 as JAN, ";
      $listobject->querystring .= "0 as FEB, ";
      $listobject->querystring .= "0 as MAR, ";
      $listobject->querystring .= "0 as APR, ";
      $listobject->querystring .= "0 as MAY, ";
      $listobject->querystring .= "0 as JUN, ";
      $listobject->querystring .= "0 as JUL, ";
      $listobject->querystring .= "0 as AUG, ";
      $listobject->querystring .= "0 as SEP, ";
      $listobject->querystring .= "0 as OCT, ";
      $listobject->querystring .= "0 as NOV, ";
      $listobject->querystring .= "0 as DEC  ";
      $listobject->querystring .= "    from worksublu as b, ";
      $listobject->querystring .= "         worklanduses as c ";
      $listobject->querystring .= "    where b.luname = c.hspflu ";
      $listobject->querystring .= "       and b.luarea > 0 ";
      $listobject->querystring .= "       and b.sublu not in (select sublu from montotal) ";
      $listobject->performQuery();
      */


      $listobject->querystring = "update montotal set totalapp = ";
      $listobject->querystring .= "annualapplied * luarea";
      $listobject->performQuery();
      $listobject->debug = $prevdebug;

   }

   function makeMonLoadCharTable($listobject, $projectid, $debug) {

      # create a general table pulling together the characteristics
      # of the various loads by subwatershed
      # this table unites the sourceloadtype table with the sources table
      # including the source population, source production per AU/day
      $listobject->querystring = "create temp table monsubloadchars as select a.sourceid, a.avgweight, a.sourcename, a.distrotype, b.subshedid, b.sourcepop as popdens, b.sourcepop as actualpop, c.pollutantconc, c.pollutantprod, c.conv, c.auweight, c.typeid, c.sourceclass, c.starttime, c.duration, (b.sourcepop * a.avgweight / c.auweight) as aucount,  1.0 as meanpopfact, ";
      $listobject->querystring .= "    1.0 as JAN, 1.0 as FEB, 1.0 as MAR, 1.0 as APR,";
      $listobject->querystring .= "    1.0 as MAY, 1.0 as JUN, 1.0 as JUL, 1.0 as AUG,";
      $listobject->querystring .= "    1.0 as SEP, 1.0 as OCT, 1.0 as NOV, 1.0 as DEC";
      $listobject->querystring .= "    from sources as a,";
      $listobject->querystring .= "         subshed as b,";
      $listobject->querystring .= "         sourceloadtype as c";
      $listobject->querystring .= "    where ";
      $listobject->querystring .= "        a.projectid = $projectid";
      $listobject->querystring .= "    and a.distrotype not in (10)";
      $listobject->querystring .= "    and b.projectid = $projectid";
      $listobject->querystring .= "    and c.projectid = $projectid";
      $listobject->querystring .= "    and b.sourceid = a.sourceid";
      $listobject->querystring .= "    and c.typeid = a.typeid";

      if ($debug == 1) {
      #print("$listobject->querystring ; <br>");
      }

      $listobject->performQuery();

      $listobject->querystring = "update monsubloadchars set ";
      $listobject->querystring .= " JAN = (a.actualpop * b.JAN * a.conv * a.pollutantconc * a.pollutantprod * (a.avgweight / a.auweight) ), ";
      $listobject->querystring .= " FEB = (a.actualpop * b.FEB * a.conv * a.pollutantconc  * a.pollutantprod * (a.avgweight / a.auweight) ),";
      $listobject->querystring .= " MAR = (a.actualpop * b.MAR * a.conv * a.pollutantconc  * a.pollutantprod * (a.avgweight / a.auweight) ),";
      $listobject->querystring .= " APR = (a.actualpop * b.APR * a.conv * a.pollutantconc  * a.pollutantprod * (a.avgweight / a.auweight) ),";
      $listobject->querystring .= " MAY = (a.actualpop * b.MAY * a.conv * a.pollutantconc  * a.pollutantprod * (a.avgweight / a.auweight) ),";
      $listobject->querystring .= " JUN = (a.actualpop * b.JUN * a.conv * a.pollutantconc  * a.pollutantprod * (a.avgweight / a.auweight) ),";
      $listobject->querystring .= " JUL = (a.actualpop * b.JUL * a.conv * a.pollutantconc  * a.pollutantprod * (a.avgweight / a.auweight) ),";
      $listobject->querystring .= " AUG = (a.actualpop * b.AUG * a.conv * a.pollutantconc  * a.pollutantprod * (a.avgweight / a.auweight) ),";
      $listobject->querystring .= " SEP = (a.actualpop * b.SEP * a.conv * a.pollutantconc  * a.pollutantprod * (a.avgweight / a.auweight) ),";
      $listobject->querystring .= " OCT = (a.actualpop * b.OCT * a.conv * a.pollutantconc  * a.pollutantprod * (a.avgweight / a.auweight) ),";
      $listobject->querystring .= " NOV = (a.actualpop * b.NOV * a.conv * a.pollutantconc  * a.pollutantprod * (a.avgweight / a.auweight) ),";
      $listobject->querystring .= " DEC = (a.actualpop * b.DEC * a.conv * a.pollutantconc  * a.pollutantprod * (a.avgweight / a.auweight) )";
      $listobject->querystring .= "   from monsubloadchars as a,";
      $listobject->querystring .= "   monthlydistro as b";
      $listobject->querystring .= "   where b.projectid = $projectid and";
      $listobject->querystring .= "         a.sourceid = b.sourceid and";
      $listobject->querystring .= "         monsubloadchars.sourceid = a.sourceid and";
      $listobject->querystring .= "         monsubloadchars.subshedid = a.subshedid and";
      # monthly population fluctuation is spreadid 3
      $listobject->querystring .= "         b.spreadid = 3";

      $listobject->performQuery();

      $listobject->querystring = "update monsubloadchars set meanpopfact = ((b.JAN + b.FEB + b.MAR + b.APR + b.MAY + b.JUN + b.JUL + b.AUG + b.SEP + b.OCT + b.NOV + b.DEC ) / 12.0)  from monthlydistro as b where b.sourceid = monsubloadchars.sourceid and b.projectid = $projectid and b.spreadid = 3";
      $listobject->performQuery();


      $listobject->querystring = "select * from monsubloadchars order by subshedid, sourcename";
      $listobject->performQuery();
      if ($debug == 1) {
         $listobject->showList();
      }

   }

   function calcWaterLoads($listobject, $projectid, $debug) {


      # create a table that unites the sourceloadtype table with the sources table
      # including the source population, source production per AU/day
      # and any population fluctuations by month
      makeLoadCharTable($listobject, $projectid, $debug);

      # create a table that has the percentage to water by month for each source,
      # include the source type
      calcMultiHab($listobject, $projectid, $debug);

      # create a table that has the percentage to water by month for each source,
      # include the source type
      $listobject->querystring = "update genhab set sublupop = a.popdens * weightedhab from subloadchars as a where genhab.sourceid = a.sourceid and genhab.subshedid = a.subshedid";
      $listobject->performQuery();

      $listobject->querystring = "update subloadchars set actualpop = popdens * a.subshedhab from gensubhab as a where subloadchars.sourceid = a.sourceid and subloadchars.subshedid = a.subshedid";
      $listobject->performQuery();
      if ($debug == 1) {
         print("<b>Sources and waste production characteristics, by sub-watershed</b><br>");
         $listobject->querystring = "select * from subloadchars order by subshedid";
         $listobject->performQuery();
         $listobject->showList();
      }



      # create a direct load table, taking into account monthly population fluctuations
      # and monthly estimated percentage direct deposition
      # keep each source inidividual
      $listobject->querystring = "create temp table subwaterbysource as (select ";
      $listobject->querystring .= "      a.subshedid as subshedid, a.sourcename, a.sourceid, a.sourceclass, a.distrotype, a.starttime, a.duration, a.actualpop, a.pollutantconc, a.pollutantprod, a.conv, a.avgweight, a.auweight, (a.actualpop * a.pollutantprod * (a.avgweight / a.auweight)) as actualprod, ";
      $listobject->querystring .= "      ((c.JAN + c.FEB + c.MAR + c.APR + c.MAY + c.JUN + c.JUL + c.AUG + c.SEP + c.OCT + c.NOV + c.DEC)/12.0) as avgpct,";
      $listobject->querystring .= "      ((b.JAN + b.FEB + b.MAR + b.APR + b.MAY + b.JUN + b.JUL + b.AUG + b.SEP + b.OCT + b.NOV + b.DEC)/12.0) as meanpopfact,";
      $listobject->querystring .= "      (a.actualpop * b.JAN * c.JAN * a.conv * a.pollutantconc  * a.pollutantprod * (a.avgweight / a.auweight) ) as JAN,";
      $listobject->querystring .= "      (a.actualpop * b.FEB * c.FEB * a.conv * a.pollutantconc  * a.pollutantprod * (a.avgweight / a.auweight) ) as FEB,";
      $listobject->querystring .= "      (a.actualpop * b.MAR * c.MAR * a.conv * a.pollutantconc  * a.pollutantprod * (a.avgweight / a.auweight) ) as MAR,";
      $listobject->querystring .= "      (a.actualpop * b.APR * c.APR * a.conv * a.pollutantconc  * a.pollutantprod * (a.avgweight / a.auweight) ) as APR,";
      $listobject->querystring .= "      (a.actualpop * b.MAY * c.MAY * a.conv * a.pollutantconc  * a.pollutantprod * (a.avgweight / a.auweight) ) as MAY,";
      $listobject->querystring .= "      (a.actualpop * b.JUN * c.JUN * a.conv * a.pollutantconc  * a.pollutantprod * (a.avgweight / a.auweight) )as JUN,";
      $listobject->querystring .= "      (a.actualpop * b.JUL * c.JUL * a.conv * a.pollutantconc  * a.pollutantprod * (a.avgweight / a.auweight) ) as JUL,";
      $listobject->querystring .= "      (a.actualpop * b.AUG * c.AUG * a.conv * a.pollutantconc  * a.pollutantprod * (a.avgweight / a.auweight) ) as AUG,";
      $listobject->querystring .= "      (a.actualpop * b.SEP * c.SEP * a.conv * a.pollutantconc  * a.pollutantprod * (a.avgweight / a.auweight) ) as SEP,";
      $listobject->querystring .= "      (a.actualpop * b.OCT * c.OCT * a.conv * a.pollutantconc  * a.pollutantprod * (a.avgweight / a.auweight) ) as OCT,";
      $listobject->querystring .= "      (a.actualpop * b.NOV * c.NOV * a.conv * a.pollutantconc  * a.pollutantprod * (a.avgweight / a.auweight) ) as NOV,";
      $listobject->querystring .= "      (a.actualpop * b.DEC * c.DEC * a.conv * a.pollutantconc  * a.pollutantprod * (a.avgweight / a.auweight) ) as DEC";
      $listobject->querystring .= "   from subloadchars as a,";
      $listobject->querystring .= "        monthlydistro as b,";
      $listobject->querystring .= "        monthlydistro as c";
      $listobject->querystring .= "   where b.projectid = $projectid and";
      $listobject->querystring .= "         c.projectid = $projectid and";
      $listobject->querystring .= "         b.sourceid = a.sourceid and";
      $listobject->querystring .= "         c.sourceid = a.sourceid and";
      # monthly population fluctuation is spreadid 3
      $listobject->querystring .= "         b.spreadid = 3 and";
      # monthly population load percentage is spreadid 1
      $listobject->querystring .= "         c.spreadid = 1 and";
      # water is landuse 13, so this gets all landuseids that are #13
      $listobject->querystring .= "         c.landuseid in (select luid from landuses where landuseid = 13)";
      $listobject->querystring .= "   )";
      $listobject->performQuery();
      if ($debug == 1) {
         print("<b>Direct To water loads, by source</b><br>");
         $listobject->querystring = "select * from subwaterbysource order by subshedid";
         $listobject->tablename = 'subwaterbysource';
         $listobject->performQuery();
         $listobject->showList();
      }

   }

   function calcMultiHab($listobject, $projectid, $debug) {

      # set up the habitat table to calculate populations for generic multiload animals
      createHabitatFactorTable($listobject, $projectid, $debug);
      $listobject->querystring = "select * from hab_sum";
      $listobject->performQuery();
      if ($debug == 1) {
         print("<b>Habitat summary table:</b><br>");
         $listobject->showList();
      }

      # create a table of wildlife habitat by sublu
      $listobject->querystring = "create temp table genhab as select a.sublu, ";
      $listobject->querystring .= " a.subshedid, b.sourceid, b.freq_likelihood, ";
      $listobject->querystring .= "b.freq_area,b.infreq_likelihood ,b.infreq_area";
      $listobject->querystring .= "       from subluparams as a,";
      $listobject->querystring .= "            habitat as b";
      $listobject->querystring .= "       where a.projectid = $projectid";
      $listobject->querystring .= "         and b.projectid = $projectid";
      $listobject->querystring .= "         and a.paramtype = 'parameter'";
      $listobject->querystring .= "         and a.sublu = b.sublu";
      $listobject->performQuery();
      $listobject->querystring = "alter table genhab add column weightedhab float8";
      $listobject->performQuery();
      $listobject->querystring = "alter table genhab add column sublupop float8";
      $listobject->performQuery();
      $listobject->querystring = "update genhab set weightedhab = (a.kfactor * (freq_likelihood * freq_area + infreq_likelihood * infreq_area)) from hab_sum as a where a.sourceid = genhab.sourceid";
      $listobject->performQuery();

      if ($debug == 1) {
         $listobject->querystring = "select * from genhab order by subshedid";
         $listobject->performQuery();
         $listobject->showList();
      }

      # create a table of wildlife populations by subshed
      $listobject->querystring = "create temp table gensubhab as select subshedid, sourceid, sum(weightedhab) as subshedhab";
      $listobject->querystring .= "       from genhab";
      $listobject->querystring .= "       group by subshedid, sourceid";
      $listobject->performQuery();

      if ($debug == 1) {
         $listobject->querystring = "select * from gensubhab order by subshedid";
         $listobject->performQuery();
         $listobject->showList();
      }


   }

   function createHabitatFactorTable($listobject, $projectid, $debug) {

      # create habSumTbl

      if (!( $listobject->tableExists('hab_sum') )) {

         $listobject->querystring = "create temp table hab_sum as (select sum(freq_area) as farea, sum(infreq_area) as iarea, avg(freq_likelihood) as flike, avg(infreq_likelihood) as inlike, sum(freq_area + infreq_area) as tarea, sourceid from habitat where projectid = $projectid group by sourceid)";
         $listobject->performQuery();

         if ($debug == 1) {
            print("<b>Hab summary Table:</b> $listobject->querystring<br>");
         }

         $listobject->querystring = "alter table hab_sum add column kfactor float8";
         $listobject->performQuery();

         $listobject->querystring = "update hab_sum set kfactor = (tarea/(flike*farea + inlike*iarea));";
         $listobject->performQuery();
      }

   }

   function genMultiLoad($listobject, $projectid, $debug) {


      createHabitatFactorTable($listobject, $projectid, $debug);

      if ($debug == 1) {
         print("<b>Habitat summary table:</b><br>");
         $listobject->querystring = "select * from hab_sum";
         $listobject->performQuery();
         $listobject->showList();
      }

      # add loads from generic multi-habitat source (generally wildlife)
      $listobject->querystring = "create temp table multi_load as (select ";
      $listobject->querystring .= "      c.sublu as perlndid,";
      $listobject->querystring .= "      sum ( (1.0 - i.JAN) * e.kfactor * d.JAN * a.sourcepop * h.conv * h.pollutantconc  * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as JAN,";
      $listobject->querystring .= "      sum ( (1.0 - i.FEB) * e.kfactor * d.FEB * a.sourcepop * h.conv * h.pollutantconc  * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as FEB,";
      $listobject->querystring .= "      sum ( (1.0 - i.MAR) * e.kfactor * d.MAR * a.sourcepop * h.conv * h.pollutantconc  * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as MAR,";
      $listobject->querystring .= "      sum ( (1.0 - i.APR) * e.kfactor * d.APR * a.sourcepop * h.conv * h.pollutantconc  * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as APR,";
      $listobject->querystring .= "      sum ( (1.0 - i.MAY) * e.kfactor * d.MAY * a.sourcepop * h.conv * h.pollutantconc  * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as MAY,";
      $listobject->querystring .= "      sum ( (1.0 - i.JUN) * e.kfactor * d.JUN * a.sourcepop * h.conv * h.pollutantconc  * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as JUN,";
      $listobject->querystring .= "      sum ( (1.0 - i.JUL) * e.kfactor * d.JUL * a.sourcepop * h.conv * h.pollutantconc  * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as JUL,";
      $listobject->querystring .= "      sum ( (1.0 - i.AUG) * e.kfactor * d.AUG * a.sourcepop * h.conv * h.pollutantconc  * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as AUG,";
      $listobject->querystring .= "      sum ( (1.0 - i.SEP) * e.kfactor * d.SEP * a.sourcepop * h.conv * h.pollutantconc  * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as SEP,";
      $listobject->querystring .= "      sum ( (1.0 - i.OCT) * e.kfactor * d.OCT * a.sourcepop * h.conv * h.pollutantconc  * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as OCT,";
      $listobject->querystring .= "      sum ( (1.0 - i.NOV) * e.kfactor * d.NOV * a.sourcepop * h.conv * h.pollutantconc  * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as NOV,";
      $listobject->querystring .= "      sum ( (1.0 - i.DEC) * e.kfactor * d.DEC * a.sourcepop * h.conv * h.pollutantconc  * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as DEC";
      $listobject->querystring .= "   from subshed as a,";
      $listobject->querystring .= "        habitat as b,";
      $listobject->querystring .= "        subluparams as c,";
      $listobject->querystring .= "        monthlydistro as d,";
      $listobject->querystring .= "        hab_sum as e,";
      $listobject->querystring .= "        sources as f,";
      $listobject->querystring .= "        sourceloadtype as h,";
      $listobject->querystring .= "        monthlydistro as i";
      $listobject->querystring .= "   where a.projectid = $projectid and";
      $listobject->querystring .= "         b.projectid = $projectid and";
      $listobject->querystring .= "         c.projectid = $projectid and";
      $listobject->querystring .= "         d.projectid = $projectid and";
      $listobject->querystring .= "         f.projectid = $projectid and";
      $listobject->querystring .= "         h.projectid = $projectid and";
      $listobject->querystring .= "         i.projectid = $projectid and";
      $listobject->querystring .= "         a.subshedid = c.subshedid and";
      $listobject->querystring .= "         c.projectid = $projectid and";
      $listobject->querystring .= "         b.sublu = c.sublu and";
      $listobject->querystring .= "         a.sourceid = b.sourceid and";
      $listobject->querystring .= "         d.sourceid = b.sourceid and";
      $listobject->querystring .= "         i.sourceid = b.sourceid and";
      $listobject->querystring .= "         e.sourceid = b.sourceid and";
      $listobject->querystring .= "         f.sourceid = b.sourceid and";
      $listobject->querystring .= "         c.paramtype = 'parameter' and";
      $listobject->querystring .= "         d.spreadid = 3 and";
      $listobject->querystring .= "         i.spreadid = 1 and";
      # distroype 9 is multi-habitat species (usually wildlife)
      $listobject->querystring .= "         f.distrotype = 9 and";
      $listobject->querystring .= "         f.typeid = h.typeid";
      $listobject->querystring .= "   group by c.sublu)";
      #print("$listobject->querystring ; <br>");
      $listobject->performQuery();

      # add loads from generic multi-habitat source (generally wildlife)
      $listobject->querystring = "create temp table sourcemulti_load as (select ";
      $listobject->querystring .= "      a.sourceid, c.sublu as perlndid,";
      $listobject->querystring .= "      sum ( (1.0 - i.JAN) * e.kfactor * d.JAN * a.sourcepop * h.conv * h.pollutantconc  * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as JAN,";
      $listobject->querystring .= "      sum ( (1.0 - i.FEB) * e.kfactor * d.FEB * a.sourcepop * h.conv * h.pollutantconc  * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as FEB,";
      $listobject->querystring .= "      sum ( (1.0 - i.MAR) * e.kfactor * d.MAR * a.sourcepop * h.conv * h.pollutantconc  * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as MAR,";
      $listobject->querystring .= "      sum ( (1.0 - i.APR) * e.kfactor * d.APR * a.sourcepop * h.conv * h.pollutantconc  * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as APR,";
      $listobject->querystring .= "      sum ( (1.0 - i.MAY) * e.kfactor * d.MAY * a.sourcepop * h.conv * h.pollutantconc  * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as MAY,";
      $listobject->querystring .= "      sum ( (1.0 - i.JUN) * e.kfactor * d.JUN * a.sourcepop * h.conv * h.pollutantconc  * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as JUN,";
      $listobject->querystring .= "      sum ( (1.0 - i.JUL) * e.kfactor * d.JUL * a.sourcepop * h.conv * h.pollutantconc  * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as JUL,";
      $listobject->querystring .= "      sum ( (1.0 - i.AUG) * e.kfactor * d.AUG * a.sourcepop * h.conv * h.pollutantconc  * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as AUG,";
      $listobject->querystring .= "      sum ( (1.0 - i.SEP) * e.kfactor * d.SEP * a.sourcepop * h.conv * h.pollutantconc  * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as SEP,";
      $listobject->querystring .= "      sum ( (1.0 - i.OCT) * e.kfactor * d.OCT * a.sourcepop * h.conv * h.pollutantconc  * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as OCT,";
      $listobject->querystring .= "      sum ( (1.0 - i.NOV) * e.kfactor * d.NOV * a.sourcepop * h.conv * h.pollutantconc  * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as NOV,";
      $listobject->querystring .= "      sum ( (1.0 - i.DEC) * e.kfactor * d.DEC * a.sourcepop * h.conv * h.pollutantconc  * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as DEC";
      $listobject->querystring .= "   from subshed as a,";
      $listobject->querystring .= "        habitat as b,";
      $listobject->querystring .= "        subluparams as c,";
      $listobject->querystring .= "        monthlydistro as d,";
      $listobject->querystring .= "        hab_sum as e,";
      $listobject->querystring .= "        sources as f,";
      $listobject->querystring .= "        sourceloadtype as h,";
      $listobject->querystring .= "        monthlydistro as i";
      $listobject->querystring .= "   where a.projectid = $projectid and";
      $listobject->querystring .= "         b.projectid = $projectid and";
      $listobject->querystring .= "         c.projectid = $projectid and";
      $listobject->querystring .= "         d.projectid = $projectid and";
      $listobject->querystring .= "         f.projectid = $projectid and";
      $listobject->querystring .= "         h.projectid = $projectid and";
      $listobject->querystring .= "         i.projectid = $projectid and";
      $listobject->querystring .= "         a.subshedid = c.subshedid and";
      $listobject->querystring .= "         c.projectid = $projectid and";
      $listobject->querystring .= "         b.sublu = c.sublu and";
      $listobject->querystring .= "         a.sourceid = b.sourceid and";
      $listobject->querystring .= "         d.sourceid = b.sourceid and";
      $listobject->querystring .= "         i.sourceid = b.sourceid and";
      $listobject->querystring .= "         e.sourceid = b.sourceid and";
      $listobject->querystring .= "         f.sourceid = b.sourceid and";
      $listobject->querystring .= "         c.paramtype = 'parameter' and";
      $listobject->querystring .= "         d.spreadid = 3 and";
      $listobject->querystring .= "         i.spreadid = 1 and";
      # distroype 9 is multi-habitat species (usually wildlife)
      $listobject->querystring .= "         f.distrotype = 9 and";
      $listobject->querystring .= "         f.typeid = h.typeid";
      $listobject->querystring .= "   group by a.sourceid, c.sublu)";
      #print("$listobject->querystring ; <br>");
      $listobject->performQuery();

      # loads to water land-uses
      # add loads from generic multi-habitat source (generally wildlife)
      $listobject->querystring = "create temp table multi_load_water as (select ";
      $listobject->querystring .= "      c.subshedid as subshedid,";
      $listobject->querystring .= "      sum ( i.JAN * e.kfactor * d.JAN * a.sourcepop * h.pollutantconc * h.conv  * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as JAN,";
      $listobject->querystring .= "      sum ( i.FEB * e.kfactor * d.FEB * a.sourcepop * h.pollutantconc * h.conv * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as FEB,";
      $listobject->querystring .= "      sum ( i.MAR * e.kfactor * d.MAR * a.sourcepop * h.pollutantconc * h.conv * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as MAR,";
      $listobject->querystring .= "      sum ( i.APR * e.kfactor * d.APR * a.sourcepop * h.pollutantconc * h.conv * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as APR,";
      $listobject->querystring .= "      sum ( i.MAY * e.kfactor * d.MAY * a.sourcepop * h.pollutantconc * h.conv * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as MAY,";
      $listobject->querystring .= "      sum ( i.JUN * e.kfactor * d.JUN * a.sourcepop * h.pollutantconc * h.conv * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as JUN,";
      $listobject->querystring .= "      sum ( i.JUL * e.kfactor * d.JUL * a.sourcepop * h.pollutantconc * h.conv * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as JUL,";
      $listobject->querystring .= "      sum ( i.AUG * e.kfactor * d.AUG * a.sourcepop * h.pollutantconc * h.conv * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as AUG,";
      $listobject->querystring .= "      sum ( i.SEP * e.kfactor * d.SEP * a.sourcepop * h.pollutantconc * h.conv * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as SEP,";
      $listobject->querystring .= "      sum ( i.OCT * e.kfactor * d.OCT * a.sourcepop * h.pollutantconc * h.conv * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as OCT,";
      $listobject->querystring .= "      sum ( i.NOV * e.kfactor * d.NOV * a.sourcepop * h.pollutantconc * h.conv * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as NOV,";
      $listobject->querystring .= "      sum ( i.DEC * e.kfactor * d.DEC * a.sourcepop * h.pollutantconc * h.conv * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as DEC";
      $listobject->querystring .= "   from subshed as a,";
      $listobject->querystring .= "        habitat as b,";
      $listobject->querystring .= "        subluparams as c,";
      $listobject->querystring .= "        monthlydistro as d,";
      $listobject->querystring .= "        hab_sum as e,";
      $listobject->querystring .= "        sources as f,";
      $listobject->querystring .= "        sourceloadtype as h,";
      $listobject->querystring .= "        monthlydistro as i";
      $listobject->querystring .= "   where a.projectid = $projectid and";
      $listobject->querystring .= "         b.projectid = $projectid and";
      $listobject->querystring .= "         c.projectid = $projectid and";
      $listobject->querystring .= "         d.projectid = $projectid and";
      $listobject->querystring .= "         f.projectid = $projectid and";
      $listobject->querystring .= "         h.projectid = $projectid and";
      $listobject->querystring .= "         i.projectid = $projectid and";
      $listobject->querystring .= "         a.subshedid = c.subshedid and";
      $listobject->querystring .= "         b.sublu = c.sublu and";
      $listobject->querystring .= "         a.sourceid = b.sourceid and";
      $listobject->querystring .= "         d.sourceid = b.sourceid and";
      $listobject->querystring .= "         i.sourceid = b.sourceid and";
      $listobject->querystring .= "         e.sourceid = b.sourceid and";
      $listobject->querystring .= "         f.sourceid = b.sourceid and";
      $listobject->querystring .= "         d.spreadid = 3 and";
      $listobject->querystring .= "         i.spreadid = 1 and";
      $listobject->querystring .= "         f.distrotype = 9 and";
      $listobject->querystring .= "         c.paramtype = 'parameter' and";
      $listobject->querystring .= "         f.typeid = h.typeid";
      $listobject->querystring .= "   group by c.subshedid)";
      $listobject->performQuery();
      if ($debug == 1) {
         $listobject->querystring = "select * from multi_load_water";
         $listobject->tablename = 'hspf_load_table';
         $listobject->performQuery();
         print("<b>Total direct to water loads from Generic Multi-habitat sources for HSPF input:</b><br>");
         $listobject->showList();
         $listobject->querystring = "select sum(JAN) as JAN, sum(FEB) as FEB from multi_load_water";
         $listobject->tablename = 'hspf_load_table';
         $listobject->performQuery();
         print("<b>input:</b><br>");
         $listobject->showList();
         $listobject->querystring = "select sum(JAN) as JAN, sum(FEB) as FEB from multi_load";
         $listobject->tablename = 'hspf_load_table';
         $listobject->performQuery();
         print("<b>input:</b><br>");
         $listobject->showList();
      }

      $listobject->querystring = "update multi_load set JAN = e.JAN + b.JAN, FEB = e.FEB + b.FEB, MAR = e.MAR + b.MAR, APR = e.APR + b.APR, MAY = e.MAY + b.MAY, JUN = e.JUN + b.JUN, JUL = e.JUL + b.JUL, AUG = e.AUG + b.AUG, SEP = e.SEP + b.SEP, OCT = e.OCT + b.OCT, NOV = e.NOV + b.NOV, DEC = e.DEC + b.DEC ";
      $listobject->querystring .= "   from subluparams as a,";
      $listobject->querystring .= "        multi_load_water as b,";
      $listobject->querystring .= "        map_hspf_lu as c,";
      $listobject->querystring .= "        landuses as d,";
      $listobject->querystring .= "        multi_load as e";
      $listobject->querystring .= "   where a.projectid = $projectid and";
      $listobject->querystring .= "         b.subshedid = a.subshedid and";
      $listobject->querystring .= "         a.luname = c.hspf_lu and";
      $listobject->querystring .= "         c.projectid = $projectid and";
      $listobject->querystring .= "         d.projectid = $projectid and";
      $listobject->querystring .= "         c.project_luid = d.luid and";
      $listobject->querystring .= "         e.perlndid = a.sublu and";
      $listobject->querystring .= "         e.perlndid = multi_load.perlndid and";
      $listobject->querystring .= "         d.landuseid = 13";
      $listobject->performQuery();


      #print("$listobject->querystring ; <br>");

      if ($debug == 1) {
         $listobject->querystring = "select * from multi_load";
         $listobject->tablename = 'hspf_load_table';
         $listobject->performQuery();
         print("<b>Total loads from Generic Multi-habitat sources for HSPF input:</b><br>");
         $listobject->showList();

         $listobject->querystring = "create temp table ind_multi_load as (select ";
         $listobject->querystring .= "      c.sublu as perlndid, f.sourceid,";
         $listobject->querystring .= "      sum ( e.kfactor * d.JAN * a.sourcepop * h.pollutantconc * h.conv * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as JAN,";
         $listobject->querystring .= "      sum ( e.kfactor * d.FEB * a.sourcepop * h.pollutantconc * h.conv * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as FEB,";
         $listobject->querystring .= "      sum ( e.kfactor * d.MAR * a.sourcepop * h.pollutantconc * h.conv * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as MAR,";
         $listobject->querystring .= "      sum ( e.kfactor * d.APR * a.sourcepop * h.pollutantconc * h.conv * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as APR,";
         $listobject->querystring .= "      sum ( e.kfactor * d.MAY * a.sourcepop * h.pollutantconc * h.conv * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as MAY,";
         $listobject->querystring .= "      sum ( e.kfactor * d.JUN * a.sourcepop * h.pollutantconc * h.conv * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as JUN,";
         $listobject->querystring .= "      sum ( e.kfactor * d.JUL * a.sourcepop * h.pollutantconc * h.conv * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as JUL,";
         $listobject->querystring .= "      sum ( e.kfactor * d.AUG * a.sourcepop * h.pollutantconc * h.conv * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as AUG,";
         $listobject->querystring .= "      sum ( e.kfactor * d.SEP * a.sourcepop * h.pollutantconc * h.conv * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as SEP,";
         $listobject->querystring .= "      sum ( e.kfactor * d.OCT * a.sourcepop * h.pollutantconc * h.conv * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as OCT,";
         $listobject->querystring .= "      sum ( e.kfactor * d.NOV * a.sourcepop * h.pollutantconc * h.conv * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as NOV,";
         $listobject->querystring .= "      sum ( e.kfactor * d.DEC * a.sourcepop * h.pollutantconc * h.conv * h.pollutantprod *(b.freq_likelihood * b.freq_area + b.infreq_likelihood * b.infreq_area) * (f.avgweight / h.auweight) ) as DEC";
         $listobject->querystring .= "   from subshed as a,";
         $listobject->querystring .= "        habitat as b,";
         $listobject->querystring .= "        subluparams as c,";
         $listobject->querystring .= "        monthlydistro as d,";
         $listobject->querystring .= "        hab_sum as e,";
         $listobject->querystring .= "        sources as f,";
         $listobject->querystring .= "        sourceloadtype as h";
         $listobject->querystring .= "   where a.projectid = $projectid and";
         $listobject->querystring .= "         a.subshedid = c.subshedid and";
         $listobject->querystring .= "         c.projectid = $projectid and";
         $listobject->querystring .= "         b.sublu = c.sublu and";
         $listobject->querystring .= "         a.sourceid = b.sourceid and";
         $listobject->querystring .= "         d.sourceid = b.sourceid and";
         $listobject->querystring .= "         e.sourceid = b.sourceid and";
         $listobject->querystring .= "         f.sourceid = b.sourceid and";
         $listobject->querystring .= "         d.spreadid = 3 and";
         $listobject->querystring .= "         f.distrotype = 9 and";
         $listobject->querystring .= "         f.typeid = h.typeid";
         $listobject->querystring .= "   group by c.sublu, f.sourceid)";
         #print("$listobject->querystring ; <br>");
         $listobject->performQuery();
         $listobject->querystring = "select * from ind_multi_load";
         $listobject->tablename = 'multi_load_table';
         $listobject->performQuery();
         print("<b>Individual loads from Generic Multi-habitat sources for HSPF input, grouped by source name:</b><br>");
         $listobject->showList();

      }
   } /* end genMultiLoad() */

   function fractionalLanduseLoads($listobject, $projectid) {

      /* create temp table with loading info
         -- a (subshed) - has animal population
         -- b (monthlydistro) has amount deposited on given landuse
         -- c (sourceloadtype) has pollutant concentrations, and loading by day, and
         ypical AU weight
         -- d (sources) has actual animal weight for given source
         -- e (monthlydistro) gets population fluctuation factor info for given source
      */

      $listobject->querystring = "create temp table load_table as (";
      $listobject->querystring .= "   select ";
      $listobject->querystring .= "      a.subshedid, a.sourceid, b.landuseid,";
      $listobject->querystring .= "      sum ( b.JAN * e.JAN * c.conv * c.pollutantconc * c.pollutantprod * a.sourcepop * d.avgweight / c.auweight ) as JAN,";
      $listobject->querystring .= "      sum ( b.FEB * e.FEB * c.conv * c.pollutantconc * c.pollutantprod * a.sourcepop * d.avgweight / c.auweight ) as FEB,";
      $listobject->querystring .= "      sum ( b.MAR * e.MAR * c.conv * c.pollutantconc * c.pollutantprod * a.sourcepop * d.avgweight / c.auweight ) as MAR,";
      $listobject->querystring .= "      sum ( b.APR * e.APR * c.conv * c.pollutantconc * c.pollutantprod * a.sourcepop * d.avgweight / c.auweight ) as APR,";
      $listobject->querystring .= "      sum ( b.MAY * e.MAY * c.conv * c.pollutantconc * c.pollutantprod * a.sourcepop * d.avgweight / c.auweight ) as MAY,";
      $listobject->querystring .= "      sum ( b.JUN * e.JUN * c.conv * c.pollutantconc * c.pollutantprod * a.sourcepop * d.avgweight / c.auweight ) as JUN,";
      $listobject->querystring .= "      sum ( b.JUL * e.JUL * c.conv * c.pollutantconc * c.pollutantprod * a.sourcepop * d.avgweight / c.auweight ) as JUL,";
      $listobject->querystring .= "      sum ( b.AUG * e.AUG * c.conv * c.pollutantconc * c.pollutantprod * a.sourcepop * d.avgweight / c.auweight ) as AUG,";
      $listobject->querystring .= "      sum ( b.SEP * e.SEP * c.conv * c.pollutantconc * c.pollutantprod * a.sourcepop * d.avgweight / c.auweight ) as SEP,";
      $listobject->querystring .= "      sum ( b.OCT * e.OCT * c.conv * c.pollutantconc * c.pollutantprod * a.sourcepop * d.avgweight / c.auweight ) as OCT,";
      $listobject->querystring .= "      sum ( b.NOV * e.NOV * c.conv * c.pollutantconc * c.pollutantprod * a.sourcepop * d.avgweight / c.auweight ) as NOV,";
      $listobject->querystring .= "      sum ( b.DEC * e.DEC * c.conv * c.pollutantconc * c.pollutantprod * a.sourcepop * d.avgweight / c.auweight ) as DEC";
      $listobject->querystring .= "   from subshed as a,";
      $listobject->querystring .= "        monthlydistro as b,";
      $listobject->querystring .= "        sourceloadtype as c,";
      $listobject->querystring .= "        sources as d,";
      $listobject->querystring .= "        monthlydistro as e";
      $listobject->querystring .= "   where a.projectid = $projectid and";
      $listobject->querystring .= "         b.projectid = $projectid and";
      $listobject->querystring .= "         b.projectid = $projectid and";
      $listobject->querystring .= "         c.projectid = $projectid and";
      $listobject->querystring .= "         d.projectid = $projectid and";
      $listobject->querystring .= "         e.projectid = $projectid and";
      $listobject->querystring .= "         b.sourceid = a.sourceid and";
      $listobject->querystring .= "         a.sourceid = d.sourceid and";
      $listobject->querystring .= "         e.sourceid = a.sourceid and";
      $listobject->querystring .= "         b.spreadid = 1 and";
      $listobject->querystring .= "         e.spreadid = 3 and";
      # distroype 9 is multi-habitat species (usually wildlife)
      # distroype 10 is an intermittent load, such as biosolid or overflow
      $listobject->querystring .= "         d.distrotype not in (9, 10) and";
      $listobject->querystring .= "         d.typeid = c.typeid";
      $listobject->querystring .= "   group by a.subshedid,a.sourceid,b.landuseid)";
      $listobject->performQuery();

      $listobject->querystring = "create temp table stored_loads as (";
      $listobject->querystring .= "      select a.subshedid, a.sourceid,  ";
      $listobject->querystring .= "sum( c.storagedieoff *( a.JAN*b.JAN + a.FEB*b.FEB + a.MAR*b.MAR + a.APR*b.APR + a.MAY*b.MAY + a.JUN*b.JUN + a.JUL*b.JUL + a.AUG*b.AUG + a.SEP*b.SEP + a.OCT*b.OCT + a.NOV*b.NOV + a.DEC*b.DEC ) ) as stored";
      $listobject->querystring .= "      from load_table as a,";
      $listobject->querystring .= "           monthdays as b,";
      $listobject->querystring .= "           sourceloadtype as c,";
      $listobject->querystring .= "           sources as d,";
      $listobject->querystring .= "           landuses as e";
      $listobject->querystring .= "      where e.landuseid = 10 and";
      $listobject->querystring .= "            c.projectid = $projectid and";
      $listobject->querystring .= "            d.projectid = $projectid and";
      $listobject->querystring .= "            e.projectid = $projectid and";
      $listobject->querystring .= "            e.luid = a.landuseid and";
      $listobject->querystring .= "            a.sourceid = d.sourceid and";
      $listobject->querystring .= "            d.typeid = c.typeid";
      $listobject->querystring .= "   group by a.subshedid, a.sourceid)";
      $listobject->performQuery();


      if ($debug == 1) {
         print("<br>Loads before the addition of stored loads:<br>");
         $listobject->querystring = "select * from load_table";
        $listobject->performQuery();
         $listobject->showlist();
      }

      # copy stored loads from stored load table to load table
      # divide by number of days in the month
      $listobject->querystring = "insert into load_table (subshedid,sourceid, landuseid, JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC) ";
      $listobject->querystring .= "   select ";
      $listobject->querystring .= "      a.subshedid, a.sourceid, b.landuseid,";
      $listobject->querystring .= "      sum ( b.JAN * a.stored / c.JAN ) as JAN,";
      $listobject->querystring .= "      sum ( b.FEB * a.stored / c.FEB ) as FEB,";
      $listobject->querystring .= "      sum ( b.MAR * a.stored / c.MAR ) as MAR,";
      $listobject->querystring .= "      sum ( b.APR * a.stored / c.APR ) as APR,";
      $listobject->querystring .= "      sum ( b.MAY * a.stored / c.MAY ) as MAY,";
      $listobject->querystring .= "      sum ( b.JUN * a.stored / c.JUN ) as JUN,";
      $listobject->querystring .= "      sum ( b.JUL * a.stored / c.JUL ) as JUL,";
      $listobject->querystring .= "      sum ( b.AUG * a.stored / c.AUG ) as AUG,";
      $listobject->querystring .= "      sum ( b.SEP * a.stored / c.SEP ) as SEP,";
      $listobject->querystring .= "      sum ( b.OCT * a.stored / c.OCT ) as OCT,";
      $listobject->querystring .= "      sum ( b.NOV * a.stored / c.NOV ) as NOV,";
      $listobject->querystring .= "      sum ( b.DEC * a.stored / c.DEC ) as DEC";
      $listobject->querystring .= "   from stored_loads as a,";
      $listobject->querystring .= "        monthlydistro as b,";
      $listobject->querystring .= "        monthdays as c";
      $listobject->querystring .= "   where b.projectid = $projectid and";
      $listobject->querystring .= "         b.sourceid = a.sourceid and";
      $listobject->querystring .= "         b.spreadid = 2";
      $listobject->querystring .= "   group by a.subshedid,a.sourceid,b.landuseid";
      $listobject->performQuery();


   } /* end function fractionalLanduseLoads($listobject, $projectid) */

   function showLoads($listobject, $projectid) {

      if ( !($listobject->tableExists('load_table')) ) {
         fractionalLanduseLoads($listobject, $projectid);
      }

      $listobject->querystring = "select a.subshedid as subshedid, b.landuse as landuse, ";
      $listobject->querystring .= "       sum(a.JAN) as JAN, sum(a.FEB) as FEB, sum(a.MAR) as MAR, sum(a.APR) as APR, sum(a.MAY) as MAY, sum(a.JUN) as JUN, sum(a.JUL) as JUL, sum(a.AUG) as AUG, sum(a.SEP) as SEP, sum(a.OCT) as OCT, sum(a.NOV) as NOV, sum(a.DEC) as DEC";
      $listobject->querystring .= "    from load_table as a,";
      $listobject->querystring .= "         landuses as b";
      $listobject->querystring .= "    where a.landuseid = b.luid and";
      $listobject->querystring .= "          b.landuseid <> 10 ";
      $listobject->querystring .= "    group by a.subshedid, b.landuse";
      #$listobject->debug = 1;
      $listobject->performQuery();
      $listobject->tablename = 'load_table';
      $listobject->showList();
   } /* end function showLoads($listobject, $projectid) */

   function calcHSPFLoads($listobject, $projectid, $depwater, $calcioqcsqolim, $debug) {

      if ( !($listobject->tableExists('load_table')) ) {
         fractionalLanduseLoads($listobject, $projectid);
      }

      $listobject->querystring = "alter table load_table add column perlndid integer";
      $listobject->performQuery();

      $listobject->querystring = "update load_table set perlndid = subluparams.sublu where subluparams.luname = map_hspf_lu.hspf_lu and load_table.landuseid = map_hspf_lu.project_luid and map_hspf_lu.projectid = $projectid and subluparams.projectid = $projectid and map_hspf_lu.project_luid is not null and subluparams.subshedid = load_table.subshedid and subluparams.paramtype = 'parameter'";
      $listobject->performQuery();
      #print("$listobject->querystring ; <br>");


      $listobject->querystring = "create temp table hspf_paccum as select a.perlndid, ";
     $listobject->querystring .= "       sum(a.JAN) as JAN, sum(a.FEB) as FEB, sum(a.MAR) as MAR, sum(a.APR) as APR, sum(a.MAY) as MAY, sum(a.JUN) as JUN, sum(a.JUL) as JUL, sum(a.AUG) as AUG, sum(a.SEP) as SEP, sum(a.OCT) as OCT, sum(a.NOV) as NOV, sum(a.DEC) as DEC";
     $listobject->querystring .= "    from load_table as a,";
      $listobject->querystring .= "         landuses as b";
      $listobject->querystring .= "    where a.landuseid = b.luid and";
      $listobject->querystring .= "          b.landuseid <> 10  and";
      $listobject->querystring .= "          b.projectid = $projectid ";
     $listobject->querystring .= "    group by a.perlndid";
     #$listobject->debug = 1;
     $listobject->performQuery();
      #print("$listobject->querystring ; <br>");

      if ($debug == 1) {
         print("<b>Total loads from Stored Loads:</b><br>");
         $listobject->querystring = "select * from stored_loads order by subshedid";
         $listobject->tablename = '';
         $listobject->performQuery();
         $listobject->showList();
         print("<b>Raw loads from Land-use based Loads:</b><br>");
         $listobject->querystring = "select * from load_table order by subshedid";
         $listobject->tablename = '';
         $listobject->performQuery();
         $listobject->showList();
      }

     if ($debug == 1) {
         print("<b>Total loads from Standard Land-Use Based sources for HSPF input:</b><br>");
         $listobject->querystring = "select * from hspf_paccum order by perlndid";
         $listobject->tablename = 'hspf_load_table';
         $listobject->performQuery();
         $listobject->showList();
         $listobject->querystring = "select a.perlndid, a.sourceid, ";
         $listobject->querystring .= "       sum(a.JAN) as JAN, sum(a.FEB) as FEB, sum(a.MAR) as MAR, sum(a.APR) as APR, sum(a.MAY) as MAY, sum(a.JUN) as JUN, sum(a.JUL) as JUL, sum(a.AUG) as AUG, sum(a.SEP) as SEP, sum(a.OCT) as OCT, sum(a.NOV) as NOV, sum(a.DEC) as DEC";
         $listobject->querystring .= "    from load_table as a,";
         $listobject->querystring .= "         landuses as b";
         $listobject->querystring .= "    where a.landuseid = b.luid and";
         $listobject->querystring .= "          b.landusetype not in ( 6, 7, 8 ) ";
         $listobject->querystring .= "    group by a.perlndid, a.sourceid";
         #$listobject->debug = 1;
         $listobject->tablename = 'multi_load_table';
         print("<b>Individual loads from Standard Land-Use Based sources grouped by source for HSPF input:</b><br>");
         $listobject->performQuery();
         $listobject->showList();
      }

      $listobject->querystring = "update pmonaccum set JAN = hspf_paccum.JAN,FEB = hspf_paccum.FEB ,MAR = hspf_paccum.MAR,APR = hspf_paccum.APR,MAY = hspf_paccum.MAY,JUN = hspf_paccum.JUN,JUL = hspf_paccum.JUL,AUG = hspf_paccum.AUG,SEP = hspf_paccum.SEP,OCT = hspf_paccum.OCT,NOV = hspf_paccum.NOV,DEC = hspf_paccum.DEC where pmonaccum.segstart = hspf_paccum.perlndid";
      $listobject->performQuery();

      # do widlife calcs / generic multi-lu source
      if ( !($listobject->tableExists('multi_load')) ) {
         genMultiLoad($listobject, $projectid, $debug);
      }

      $listobject->querystring = "update pmonaccum set JAN = JAN + multi_load.JAN,FEB = FEB + multi_load.FEB ,MAR = MAR + multi_load.MAR,APR = APR + multi_load.APR,MAY = MAY + multi_load.MAY,JUN = JUN + multi_load.JUN,JUL = JUL + multi_load.JUL,AUG = AUG + multi_load.AUG,SEP = SEP + multi_load.SEP,OCT = OCT + multi_load.OCT,NOV = NOV + multi_load.NOV,DEC = DEC + multi_load.DEC where pmonaccum.segstart = multi_load.perlndid";
      $listobject->performQuery();

     $listobject->tablename = 'hspf_load_table';
      $listobject->querystring = "select * from pmonaccum order by segstart";
      $listobject->performQuery();
      if ($debug == 1) {
         print("<b>Total loads from ALL sources for HSPF input:</b><br>");
         $listobject->showList();
      }

      # make the absolute loads area weighted
      $listobject->querystring = "update pmonaccum set JAN = JAN / subluparams.luarea,FEB = FEB / subluparams.luarea, MAR = MAR / subluparams.luarea,APR = APR / subluparams.luarea,MAY = MAY / subluparams.luarea,JUN = JUN / subluparams.luarea,JUL = JUL / subluparams.luarea,AUG = AUG / subluparams.luarea,SEP = SEP / subluparams.luarea,OCT = OCT / subluparams.luarea,NOV = NOV / subluparams.luarea,DEC = DEC / subluparams.luarea where pmonaccum.segstart = subluparams.sublu and subluparams.projectid = $projectid and subluparams.paramtype = 'parameter'";
      $listobject->performQuery();

     $listobject->tablename = 'hspf_load_table';
      $listobject->querystring = "select * from pmonaccum order by segstart";
      $listobject->performQuery();
      if ($debug == 1) {
         print("<b>Area Weighted (acre/day) loads from ALL sources for HSPF input:</b><br>");
         $listobject->showList();
      }

      if (!($depwater)) {
         # no deposition on water lu's (handled as direct to stream), zero them out
         print("<br><b>Warning:</b> Deposition on water PERLND's has been set to zero.");
         $listobject->querystring = "update pmonaccum set JAN = 0, FEB = 0, MAR = 0, APR = 0, MAY = 0, JUN = 0, JUL = 0, AUG = 0, SEP = 0, OCT = 0, NOV = 0, DEC = 0 where segstart in (select sublu from subluparams where projectid = $projectid and luname in (select hspf_lu from map_hspf_lu where projectid = $projectid and project_luid in (select luid from landuses where projectid = $projectid and landuseid = 13)))";
         $listobject->performQuery();
      }

      ##################################################################
      ##################    BEGIN Reductions   #########################
      ##################################################################
      $listobject->querystring = "create temp table psqo_red as select a.sublu as segstart, a.subshedid as subshedid, a.luname as luname, 1.0 as luadj, 1.0 as JAN, 1.0 as FEB, 1.0 as MAR, 1.0 as APR, 1.0 as MAY, 1.0 as JUN, 1.0 as JUL, 1.0 as AUG, 1.0 as SEP, 1.0 as OCT, 1.0 as NOV, 1.0 as DEC from subluparams as a where projectid = $projectid and paramtype = 'parameter'";
      $listobject->performQuery();
      $listobject->querystring = "select adj_id,subwatersheds from adjustments where projectid = $projectid and paramname = 'sqo'";
      $listobject->performQuery();

      $adjs = $listobject->queryrecords;

      # get base factors without landuse adjustments, for each group of adjustments
      foreach ($adjs as $thisrec) {
         $subsheds = $thisrec['subwatersheds'];
         $adjid = $thisrec['adj_id'];
         if ($subsheds <> '') {
            $whereclause = "psqo_red.subshedid in ($subsheds) and b.adj_id = $adjid";
            $subclause = "and psqo_red.subshedid in ($subsheds)";
         } else {
            $whereclause = "b.projectid = $projectid and b.adj_id = $adjid";
            $subclause = '';
         }

         $listobject->querystring = "update psqo_red set JAN = b.JAN, FEB = b.FEB, MAR = b.MAR, APR = b.APR, MAY = b.MAY, JUN = b.JUN, JUL = b.JUL, AUG = b.AUG, SEP = b.SEP, OCT = b.OCT, NOV = b.NOV, DEC = b.DEC from adjustments as b where $whereclause";
         #print("$listobject->querystring ; <br>");
         $listobject->performQuery();

         # adjust for land use
         $listobject->querystring = "update psqo_red set luadj = b.adjfact from lu_adj as b, map_hspf_lu as c where psqo_red.luname = c.hspf_lu and c.projectid = $projectid and b.luid = c.mapid and b.adj_id = $adjid $subclause";
         #print("$listobject->querystring ; <br>");
         $listobject->performQuery();
      }

      if (count($adjs) > 0) {
         print("<br><b>Warning:</b> Load Reductions Applied to MON-ACCUM tables.");
         $listobject->querystring = "update pmonaccum set JAN = b.luadj*b.JAN*c.JAN, FEB = b.luadj*b.FEB*c.FEB, MAR = b.luadj*b.MAR*c.MAR, APR = b.luadj*b.APR*c.APR, MAY = b.luadj*b.MAY*c.MAY, JUN = b.luadj*b.JUN*c.JUN, JUL = b.luadj*b.JUL*c.JUL, AUG = b.luadj*b.AUG*c.AUG, SEP = b.luadj*b.SEP*c.SEP, OCT = b.luadj*b.OCT*c.OCT, NOV = b.luadj*b.NOV*c.NOV, DEC = b.luadj*b.DEC*c.DEC from psqo_red as b, pmonaccum as c where pmonaccum.segstart = b.segstart and c.segstart = b.segstart";
         $listobject->performQuery();
      }

      if ($debug == 1) {
         $listobject->querystring = "select * from psqo_red order by segstart";
         $listobject->performQuery();
         $listobject->showList();
      }
      ##################################################################
      ##################     END Reductions    #########################
      ##################################################################

      # copy perlnd loads to IMPLND areas
      $listobject->querystring = "update imonaccum set JAN = pmonaccum.JAN,FEB = pmonaccum.FEB, MAR = pmonaccum.MAR,APR = pmonaccum.APR,MAY = pmonaccum.MAY,JUN = pmonaccum.JUN,JUL = pmonaccum.JUL,AUG = pmonaccum.AUG,SEP = pmonaccum.SEP,OCT = pmonaccum.OCT,NOV = pmonaccum.NOV,DEC = pmonaccum.DEC where pmonaccum.segstart = imonaccum.segstart";
      $listobject->performQuery();
      $listobject->querystring = "update iqualinput set sqo = pqualinput.sqo,potfw = pqualinput.potfw,acqop = pqualinput.acqop,sqolim = pqualinput.sqolim where pqualinput.segstart = iqualinput.segstart";
      $listobject->performQuery();

      if ($debug == 1) {
         print("$listobject->querystring ; <br>");
      }

     $listobject->tablename = 'hspf_load_table';
      $listobject->querystring = "select * from imonaccum order by segstart";
      $listobject->performQuery();
      if ($debug == 1) {
         print("<b>Area Weighted (acre/day) loads from ALL sources for HSPF input:</b><br>");
         $listobject->showList();
      }

      $listobject->querystring = "create temp table psqo_tmp as select a.sublu as segstart, a.subshedid as subshedid, a.luname as luname, 1.0 as luadj, 1.0 as JAN, 1.0 as FEB, 1.0 as MAR, 1.0 as APR, 1.0 as MAY, 1.0 as JUN, 1.0 as JUL, 1.0 as AUG, 1.0 as SEP, 1.0 as OCT, 1.0 as NOV, 1.0 as DEC from subluparams as a where a.projectid = $projectid and a.paramtype = 'parameter'";
      $listobject->performQuery();

      $listobject->querystring = "select adj_id,subwatersheds from adjustments where projectid = $projectid and paramname = 'sqolim'";
      $listobject->performQuery();

      $adjs = $listobject->queryrecords;

      if (count($adjs) == 0) {
         print("<br><b>Warning:</b> There are no adjustments entered for SQOLIM, thus, SQOLIM will default to the 1 * value for ACCUM.<br>");
      }
      # get base factors without landuse adjustments, for each group of adjustments
      foreach ($adjs as $thisrec) {
         $subsheds = $thisrec['subwatersheds'];
         $adjid = $thisrec['adj_id'];
         if ($subsheds <> '') {
            $whereclause = "b.paramname = 'sqolim' and b.projectid = $projectid and psqo_tmp.subshedid in ($subsheds) and b.adj_id = $adjid";
            $subclause = "and psqo_tmp.subshedid in ($subsheds)";
         } else {
            $whereclause = "b.paramname = 'sqolim' and b.projectid = $projectid and b.adj_id = $adjid";
            $subclause = '';
         }

         $listobject->querystring = "update psqo_tmp set JAN = b.JAN, FEB = b.FEB, MAR = b.MAR, APR = b.APR, MAY = b.MAY, JUN = b.JUN, JUL = b.JUL, AUG = b.AUG, SEP = b.SEP, OCT = b.OCT, NOV = b.NOV, DEC = b.DEC from adjustments as b where $whereclause";
         #print("$listobject->querystring ; <br>");
         $listobject->performQuery();

         # adjust for land use
         $listobject->querystring = "update psqo_tmp set luadj = b.adjfact from lu_adj as b, map_hspf_lu as c where psqo_tmp.luname = c.hspf_lu and c.projectid = $projectid and b.luid = c.mapid and b.adj_id = $adjid $subclause";
         #print("$listobject->querystring ; <br>");
         $listobject->performQuery();
      }


      if ($debug == 1) {
         $listobject->querystring = "select * from psqo_tmp order by segstart";
         $listobject->performQuery();
         $listobject->tablename = '';
         $listobject->showList();
      }


      # copy from temp table to live table
      $listobject->querystring = "update pmonsqolim set JAN = b.luadj*b.JAN*c.JAN, FEB = b.luadj*b.FEB*c.FEB, MAR = b.luadj*b.MAR*c.MAR, APR = b.luadj*b.APR*c.APR, MAY = b.luadj*b.MAY*c.MAY, JUN = b.luadj*b.JUN*c.JUN, JUL = b.luadj*b.JUL*c.JUL, AUG = b.luadj*b.AUG*c.AUG, SEP = b.luadj*b.SEP*c.SEP, OCT = b.luadj*b.OCT*c.OCT, NOV = b.luadj*b.NOV*c.NOV, DEC = b.luadj*b.DEC*c.DEC from psqo_tmp as b, pmonaccum as c where pmonsqolim.segstart = b.segstart and c.segstart = b.segstart";
      $listobject->performQuery();


      # update mon-ioqc table based on sqolim if relevant
      if ($calcioqcsqolim) {

         $listobject->querystring = "create temp table ioqc_tmp as select a.sublu as segstart, a.subshedid as subshedid, a.luname as luname, 1.0 as luadj, 1.0 as JAN, 1.0 as FEB, 1.0 as MAR, 1.0 as APR, 1.0 as MAY, 1.0 as JUN, 1.0 as JUL, 1.0 as AUG, 1.0 as SEP, 1.0 as OCT, 1.0 as NOV, 1.0 as DEC from subluparams as a where a.projectid = $projectid and a.paramtype = 'parameter'";
         $listobject->performQuery();

         $listobject->querystring = "select adj_id,subwatersheds from adjustments where projectid = $projectid and paramname = 'ioqc'";
         $listobject->performQuery();

         $adjs = $listobject->queryrecords;

         if (count($adjs) == 0) {
            print("<br><b>Warning:</b> There are no adjustments entered for IOQC, thus, IOQC will default to the 1 * value for ACCUM.<br>");
         }
         # get base factors without landuse adjustments, for each group of adjustments
         foreach ($adjs as $thisrec) {
            $subsheds = $thisrec['subwatersheds'];
            $adjid = $thisrec['adj_id'];
            if ($subsheds <> '') {
               $whereclause = "b.paramname = 'ioqc' and b.projectid = $projectid and ioqc_tmp.subshedid in ($subsheds) and b.adj_id = $adjid";
               $subclause = "and ioqc_tmp.subshedid in ($subsheds)";
            } else {
               $whereclause = "b.paramname = 'ioqc' and b.projectid = $projectid and b.adj_id = $adjid";
               $subclause = '';
            }

            $listobject->querystring = "update ioqc_tmp set JAN = b.JAN, FEB = b.FEB, MAR = b.MAR, APR = b.APR, MAY = b.MAY, JUN = b.JUN, JUL = b.JUL, AUG = b.AUG, SEP = b.SEP, OCT = b.OCT, NOV = b.NOV, DEC = b.DEC from adjustments as b where $whereclause";
            #print("$listobject->querystring ; <br>");
            $listobject->performQuery();

            # adjust for land use
            $listobject->querystring = "update ioqc_tmp set luadj = b.adjfact from lu_adj as b, map_hspf_lu as c where ioqc_tmp.luname = c.hspf_lu and c.projectid = $projectid and b.luid = c.mapid and b.adj_id = $adjid $subclause";
            #print("$listobject->querystring ; <br>");
            $listobject->performQuery();
         }


         if ($debug == 1) {
            $listobject->querystring = "select * from ioqc_tmp order by segstart";
            $listobject->performQuery();
            $listobject->tablename = '';
            $listobject->showList();
         }

         $listobject->querystring = "update pmonioqc set JAN = b.luadj*b.JAN*c.JAN, FEB = b.luadj*b.FEB*c.FEB, MAR = b.luadj*b.MAR*c.MAR, APR = b.luadj*b.APR*c.APR, MAY = b.luadj*b.MAY*c.MAY, JUN = b.luadj*b.JUN*c.JUN, JUL = b.luadj*b.JUL*c.JUL, AUG = b.luadj*b.AUG*c.AUG, SEP = b.luadj*b.SEP*c.SEP, OCT = b.luadj*b.OCT*c.OCT, NOV = b.luadj*b.NOV*c.NOV, DEC = b.luadj*b.DEC*c.DEC from ioqc_tmp as b, pmonaccum as c where pmonioqc.segstart = b.segstart and c.segstart = b.segstart";
         $listobject->performQuery();
      }

     $listobject->tablename = 'hspf_load_table';
      $listobject->querystring = "select * from imonaccum order by segstart";
      $listobject->performQuery();
      print("Calculating Area Weighted (acre/day) loads from ALL sources for HSPF input.<br>");
      if ($debug == 1) {
         print("<b>Area Weighted (acre/day) loads from ALL sources for HSPF input:</b><br>");
         $listobject->showList();
      }


      if ($debug == 1) {
         $listobject->querystring = "select * from psqo_red order by segstart";
         $listobject->performQuery();
         $listobject->tablename = '';
         $listobject->showList();
      }


      # copy sqolim loads to IMPLND areas
      $listobject->querystring = "update imonsqolim set JAN = pmonsqolim.JAN,FEB = pmonsqolim.FEB, MAR = pmonsqolim.MAR,APR = pmonsqolim.APR,MAY = pmonsqolim.MAY,JUN = pmonsqolim.JUN,JUL = pmonsqolim.JUL,AUG = pmonsqolim.AUG,SEP = pmonsqolim.SEP,OCT = pmonsqolim.OCT,NOV = pmonsqolim.NOV,DEC = pmonsqolim.DEC where pmonsqolim.segstart = imonsqolim.segstart";
      $listobject->performQuery();


   } /* end function calchspfloads($listobject, $projectid) */



   function splitSegments($listobject, $projectid, $debug) {

     $outarr = array();

     $listobject->querystring = "create temp table bp_temp (reachid integer, contribreach integer, reachorder integer)";
     $listobject->performQuery();

     $listobject->querystring = "create temp table bp_all (reachid integer, contribreach integer)";
     $listobject->performQuery();

      $listobject->querystring = "select reachid,from_node from projreaches where projectid = $projectid and reachid in (select reachid from breakpoints where projectid = $projectid)";
      if ($debug == 1) { print("$listobject->querystring ; <br>"); }
      $listobject->performQuery();
      $bps = $listobject->queryrecords;

      foreach ($bps as $bp) {
         $thisbp = $bp['from_node'];
         $thisreach = $bp['reachid'];
         print("Retrieving contributing reaches for break-point at reach $thisreach (from_node = $thisbp) ...<br>");
         $listobject->querystring = "select from_node from projreaches where to_node = $thisbp and projectid = $projectid";
         if ($debug == 1) { print("$listobject->querystring ; <br>"); }
         $listobject->performQuery();

         $fnodes = "$thisbp";

         while ($fnodes <> '') {
            #$listobject->querystring = "insert into bp_temp (reachid,contribreach) select $thisreach, from_node from projreaches where projectid = $projectid and to_node in ($fnodes) and from_node not in ($fnodes)";
            # store only reachids of breakpoints that contribute to other breakpoints
            $listobject->querystring = "insert into bp_temp (reachid,contribreach) select $thisreach, reachid from projreaches where projectid = $projectid and to_node in ($fnodes) and from_node not in ($fnodes) and reachid in (select reachid from breakpoints where projectid = $projectid)";
            $listobject->performQuery();

            # store all contributing reaches for all breakpoints
            $listobject->querystring = "insert into bp_all (reachid,contribreach) select $thisreach, reachid from projreaches where projectid = $projectid and to_node in ($fnodes) and from_node not in ($fnodes)";
            $listobject->performQuery();

            $listobject->querystring = "select from_node from projreaches where to_node in ($fnodes) and from_node not in ($fnodes) and projectid = $projectid";
            $listobject->performQuery();

            if ($debug == 1) { print("$thisreach - $fnodes<br>"); }
            $frecs = $listobject->queryrecords;
            $knodes = '';
            $fdel = '';
            foreach ($frecs as $thisrec) {
               $fnode = $thisrec['from_node'];
               $knodes .= "$fdel$fnode";
               $fdel = ',';
            }
            $fnodes = $knodes;
         }
      }

     # insert first order streams, with no contribreach
     $listobject->querystring = "insert into bp_temp (reachid, contribreach, reachorder) select reachid, -1, 1 from breakpoints where projectid = $projectid and reachid not in (select reachid from bp_temp)";
      if ($debug == 1) { print("$listobject->querystring ; <br>"); }
     $listobject->performQuery();

     # calculate order for higher
     $nullcount = 1;
     while ($nullcount > 0) {
     #for ($i = 1;$i <= 2;$i++) {
        $listobject->querystring = "update bp_temp set reachorder = a.reachorder + 1  from bp_temp as a where a.reachid = bp_temp.contribreach and a.reachorder > 0";
         if ($debug == 1) { print("$listobject->querystring ; <br>"); }
        $listobject->performQuery();
        $listobject->querystring = "select count(*) as nullcount from bp_temp where reachorder is null";
         if ($debug == 1) { print("$listobject->querystring ; <br>"); }
        $listobject->performQuery();
        $nullcount = $listobject->getRecordValue(1,'nullcount');
     }

      $listobject->querystring = "select * from bp_temp";
      $listobject->performQuery();
      if ($debug == 1) {
         print("$listobject->querystring ; <br>");
         $listobject->showlist();
      }

      $listobject->querystring = "select reachid, max(reachorder) as reachorder from bp_temp group by reachid";
      $listobject->performQuery();
      if ($debug == 1) {
         print("$listobject->querystring ; <br>");
         $listobject->showlist();
      }
      $frecs = $listobject->queryrecords;
      $rwater = '';
      $fdel = '';
      foreach ($frecs as $thisrec) {
         $rnode = $thisrec['receivingwaters'];
         $rwater .= "$fdel$rnode";
         $fdel = ',';
      }

     # calculate order for higher
     $listobject->querystring = "select max(reachorder) as reachorder from bp_temp";
      if ($debug == 1) { print("$listobject->querystring ; <br>"); }
     $listobject->performQuery();
     $reachorder = $listobject->getRecordValue(1,'reachorder');

     # go through by order, performing processing on selected segments only
     # *** this could serve as a basis for splitting up the task in a multi-node
     # processing situation
     $j = 0;

     for ($i = 1;$i <= $reachorder;$i++) {
        $listobject->querystring = "select reachid from bp_temp where reachorder = $i and reachid not in (select reachid from bp_temp where reachorder > $i) group by reachid";
         if ($debug == 1) { print("$listobject->querystring ; <br>"); }
        $listobject->performQuery();

        $ordreaches = $listobject->queryrecords;

        print("<b>Breakpoints of order $i:</b><br>");

        foreach ($ordreaches as $thisrec) {
           $j++;
            $thisreach = $thisrec['reachid'];
            $listobject->querystring = "select concat_agg(contribreach::varchar) as creaches from bp_all where reachid = $thisreach and contribreach not in (select contribreach from bp_all where reachid in (select contribreach from bp_temp where reachid = $thisreach))";
            if ($debug == 1) { print("$listobject->querystring ; <br>"); }
            $listobject->performQuery();
            $creaches = $listobject->getRecordValue(1,'creaches');
            print("Unique contributing reaches for Reach $thisreach - $creaches<br>");

            $thissegment = array('reachid'=>$thisreach,'tribs'=>$creaches,'segno'=>$j);
            array_push($outarr,$thissegment);

         }

     }

     # get remaining reaches not covered by break point contributing area

     $listobject->querystring = "select concat_agg(reachid::varchar) as creaches from projreaches where reachid not in (select contribreach from bp_all) and projectid = $projectid";
     $listobject->performQuery();
     $creaches = $listobject->getRecordValue(1,'creaches');
     $j++;
     $thissegment = array('reachid'=>-1,'tribs'=>$creaches,'segno'=>$j);
     array_push($outarr,$thissegment);
     print("Remaining reaches for this project: $creaches<br>");

      return $outarr;

   }

   function reportUCIParams($m,$o) {

      $outlines = array();
      $i = 0;
      array_push($outlines, "*** Hydrology Parameter Calibration Summary:");

      $outstring = '*** ';
      foreach (array_keys($m) as $thisparam) {

         $mult = $m["$thisparam"] * 100.0;
         $off = $o["$thisparam"];
         #$base = $b["$thisparam"];
         $uname = strtoupper($thisparam);
         $i++;

         if ( ($uname == 'PROJECTID') or ($uname == 'PARAMTYPE') or ($uname == 'SUBLU') or ($uname == 'LUNAME') or ($uname == 'LUAREA') ) {
            $i--;
         } else {
            $outstring .= sprintf('%s = %3.2f%% + %2.3f; ',$uname, $mult, $off);
         }
         if ($i == 3) {
            array_push($outlines, $outstring);
            $outstring = '*** ';
            $i = 0;
         }
      }

      return $outlines;

   }

?>